[英]How to check if nvidia-gpu is available using bash script?
I want to do this我想做这个
if nvidia-gpu available; then
do something
else
do something-else
fi
How can i achieve this using bash script?我如何使用 bash 脚本来实现这一点?
It depends a little on your system and the tools installed.这在一定程度上取决于您的系统和安装的工具。 If, eg, you can use
lshw
, this would possibly be enough:例如,如果您可以使用
lshw
,这可能就足够了:
if [[ $(lshw -C display | grep vendor) =~ Nvidia ]]; then
do something
else
do something-else
fi
Explanation:解释:
lshw
lists your hardware devices lshw
列出您的硬件设备-C display
limits this to display charachteristics only -C display
将此限制为仅显示特性grep vendor
filters out the line containing vendor specification grep vendor
过滤掉包含供应商规范的行=~ Nvidia
checks if that line matches the expression "Nvidia" =~ Nvidia
检查该行是否与表达式“Nvidia”匹配If you can't use lshw
you might be able to achieve something similar using lspci
or reading values from the /proc
file system.如果您不能使用
lshw
,您可以使用lspci
或从/proc
文件系统读取值来实现类似的功能。
It might be possible, that for this to work you need to have working Nvidia drivers installed for the graphics card.您可能需要为显卡安装有效的 Nvidia 驱动程序才能正常工作。 But I assume, your use case wouldn't make sense without them anyway.
但我认为,无论如何,如果没有它们,您的用例将毫无意义。 :)
:)
If lspci
is available/acceptable.如果
lspci
可用/可接受。
#!/usr/bin/env bash
# Some distro requires that the absolute path is given when invoking lspci
# e.g. /sbin/lspci if the user is not root.
gpu=$(lspci | grep -i '.* vga .* nvidia .*')
shopt -s nocasematch
if [[ $gpu == *' nvidia '* ]]; then
printf 'Nvidia GPU is present: %s\n' "$gpu"
echo do_this
else
printf 'Nvidia GPU is not present: %s\n' "$gpu"
echo do_that
fi
Things get more complicated when dealing with dual GPU's like Optimus and the likes.当处理像 Optimus 之类的双 GPU 时,事情会变得更加复杂。
lspci | grep -i vga
Output Output
01:00.0 VGA compatible controller: NVIDIA Corporation GP107M [GeForce GTX 1050 3 GB Max-Q] (rev a1)
05:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Picasso (rev c2)
One work around is to count how many GPU's is/are available.一种解决方法是计算有多少 GPU 可用。
lspci | grep -ci vga
Output Output
2
Just add another test if there are more than one VGA output.如果有多个 VGA output,只需添加另一个测试。
total=$(lspci | grep -ci vga)
if ((total > 1)); then
echo "$total"
echo do_this
fi
I'm Using GNU grep
so, not sure if that flag will work on non GNU grep.我正在使用 GNU
grep
所以,不确定该标志是否适用于非 GNU grep。
When it is loaded with modprobe
or insmod
then you can do something like...当它加载
modprobe
或insmod
时,您可以执行类似...
(lsmod | grep -q nameofyourdriver) && echo 'already there' || echo 'load it'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.