• Uncategorized

About bash : Can-I-run-su-in-the-middle-of-a-bash-script

Question Detail

Can I change/su user in the middle of a script?

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres 
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql

Question Answer

You can, but bash won’t run the subsequent commands as postgres. Instead, do:

su postgres -c 'dropdb $user'

The -c flag runs a command as the user (see man su).

You can use a here document to embed multiple su commands in your script:

if [ "$user" == "" ]; then
  echo "Enter the table name";
  read user
fi

gunzip *
chown postgres *
su postgres <<EOSU
dropdb $user
psql -c "create database $user with encoding 'unicode';" -U dbname template1
psql -d $user -f *.sql
EOSU

Not like this. su will invoke a process, which defaults to a shell. On the command line, this shell will be interactive, so you can enter commands. In the context of a script, the shell will end right away (because it has nothing to do).

With

su user -c command

command will be executed as user – if the su succeeds, which is generally only the case with password-less users or when running the script as root.

Use sudo for a better and more fine-grained approach.

Refer to answers in below question,

You can write between << EOF and EOF as mentioned in answers.

#!/bin/bash
whoami
sudo -u someuser bash << EOF
echo "In"
whoami
EOF
echo "Out"
whoami

How do I use su to execute the rest of the bash script as that user?

No you can’t. Or atleast… you can su but su will simply open a new shell at that point and when it’s done it will continue with the rest of the script.

One way around it is to use su -c 'some command'

Another interesting idea that I heard today is to do a recursive call on the script, when you run as root and you want to run the script as another user. See the example below:

I am running script “my_script” as “root” and want the script to run as user “raamee”


#!/bin/bash

#Script name is: my_script

user=`whoami`

if [ "$user" == "root" ]; then
  # As suggested by glenn jackman. Since I don't have anything to run once 
  # switching the user, I can modify the next line to: 
  # exec sudo -u raamee my_script and reuse the same process
  sudo -u raamee my_script
fi

if [ "$user" == "raamee" ]; then
  #put here the commands you want to perform
  do_command_1
  do_command_2
  do_command_3
fi

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.