Search code examples
linuxbashubunturbenv

Checking for installed software with sudo


I've put together a simple bash script to see if rbenv is installed. I installed rbenv system-wide instead of per-user using this guide and confirmed it's installed for both users:

user@ubuntu:~$ rbenv version
2.1.4 (set by /usr/local/rbenv/version)

user@ubuntu:~$ sudo -i
root@ubuntu:~$ rbenv version
2.1.4 (set by /usr/local/rbenv/version)

I have to check if it is installed for the root user because I am doing system admin jobs within the script:

#!/bin/bash

exec 5> debug_output.txt
BASH_XTRACEFD="5"

[ $UID != 0 ] && exec sudo $0 "$@"

if [[ ! `rbenv version | grep "2.1.4"` ]]; then
    echo "rbenv not installed ... do something"
else
    echo "rbenv installed"
fi

However, when I run the script for the normal user context (using sudo):

user@aaabbbccc:~$ sudo ./test.sh
./test.sh: line 5: rbenv: command not found
rbenv not installed ... do something

Why is my script not picking up the context for the root user and detecting that rbenv is actually installed?

Update: added Debug output

+ '[' 0 '!=' 0 ']'
++ grep 2.1.4
++ rbenv version
+ [[ ! -n '' ]]
+ echo 'rbenv not installed'

Solution

  • /usr/local/ (or wherever rbenv executable is installed) is not in your user's executable path when sudo runs. Use -i or add /usr/local/ to your $PATH.