I need to check for a directory in the home directory of another user. Normally I would sudo but that forks another process and I also lose my environment.
For example, I have:
if [[ -d "/home/otheruser/svn" ]];
then
echo "SVN exists"
else
echo "SVN does not exist"
fi
I need the the test condition to run with root permissions.
You need to run it under a subshell. Example:
if sudo bash -c '[[ -d "/home/otheruser/svn" ]]'
then
echo "SVN exists"
else
echo "SVN does not exist"
fi
Note that if you are using -d
specifically (or any of the other operators supported by /bin/test
) then using sudo test
is better and safer, as shown in the other answer.
Very importantly, however, /bin/test
is not exactly the same as the bash builtin test
which is not exactly the same as the bash builtin [[
. If you need to execute a shell builtin for your conditional expression—for example, if you need the pattern-matching behavior of ==
or =~
, the locale-aware lexicographical sorting provided by <
and >
, the &&
and ||
short-circuiting operators, or other subtly different behavior from [[
, the only way to do this is with a privileged subshell, as shown.
Most importantly of all, if you need to use a variable in your expression, do not simply drop that variable into the string to be executed by sudo. One safe way to pass a variable to a test in a sudo subshell is with --preserve-env
. Example:
export MYDIR=/home/otheruser/svn
if sudo --preserve-env=MYDIR bash -c '[[ -d "$MYDIR" ]]'
then
...
The use of single and double quotes as shown is vital. The single quotes on the outside keeps MYDIR from being interpolated until the string inside is evaluated by the subshell, and the double quotes on the inside keep MYDIR as a single argument to the -d
operator, in case it contains spaces or other weird shell metacharacters.[*]
[*] Yes, the double quotes are not really necessary here. Bash does not perform word splitting on the stuff between [[
and ]]
. But that's confusing to explain and more detail than this post needs, and it's good to get into the habit of always quoting variables where possible.