Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sudo if in Bash?

Tags:

bash

shell

sudo

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.

like image 845
Dan S Avatar asked May 17 '12 18:05

Dan S


People also ask

How do I use sudo command?

In most Linux distributions, the sudo package is installed by default. To use sudo, let's just type sudo and press enter. If sudo is installed, the sudo package usage details will be displayed. If it's not, a “command not found” message will be displayed.

What is the meaning of if in bash?

If you are just starting to explore the Bash coding language, you will soon find yourself wanting to create conditional statements. Conditional statements, in other words, define 'if a condition is true or false, then do this or that, and if the opposite is true, do something else'.

How do I run a command as root in bash?

To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....


2 Answers

if sudo test -d "/home/otheruser/svn"; then
like image 135
paulmelnikow Avatar answered Oct 06 '22 08:10

paulmelnikow


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
like image 44
the paul Avatar answered Oct 06 '22 07:10

the paul