Search code examples
bashshellsudo

How do I sudo if in Bash?


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.


Solution

  • 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