1

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?

Leo
  • 480
  • 1
  • 6
  • 9
  • Does this answer your question? [How can I check if a program exists from a Bash script?](https://stackoverflow.com/questions/592620/how-can-i-check-if-a-program-exists-from-a-bash-script) – iBug Mar 13 '21 at 08:24
  • @iBug, The actual question is what command should i use to validate if gpu is available or not?. Ex: nvidia-smi or nvcc, but these commands will always be available if you have gpu plugged in or not, so we cannot use this. – Leo Mar 13 '21 at 08:29
  • nvidia-smi reports required information – user7860670 Mar 13 '21 at 08:50

3 Answers3

1

It depends a little on your system and the tools installed. If, e. g., you can use lshw, this would possibly be enough:

if [[ $(lshw -C display | grep vendor) =~ Nvidia ]]; then
  do something
else
  do something-else
fi

Explanation:

  • lshw lists your hardware devices
  • -C display limits this to display charachteristics only
  • grep vendor filters out the line containing vendor specification
  • =~ Nvidia checks if that line matches the expression "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.

It might be possible, that for this to work you need to have working Nvidia drivers installed for the graphics card. But I assume, your use case wouldn't make sense without them anyway. :)

ahuemmer
  • 1,653
  • 9
  • 22
  • 29
1

If lspci is available/acceptable.

#!/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.

lspci | grep -i vga

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.

lspci | grep -ci vga

Output

2

Just add another test if there are more than one 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.

Jetchisel
  • 7,493
  • 2
  • 19
  • 18
0

When it is loaded with modprobe or insmod then you can do something like...

(lsmod | grep -q nameofyourdriver) && echo 'already there' || echo 'load it'
koyaanisqatsi
  • 2,585
  • 2
  • 8
  • 15