简体   繁体   中英

Why does my shell script exit after changing users?

I am trying to create this little script to basically recreate the steps I take everytime I start a new ubuntu machine and install some python project on it. At one point the script stops. Which is when I switch to the postgres user. It never runs the psql commands

pip install --upgrade pip
sudo pip install virtualenv
useradd -m -p $2 $1
sudo -i -u postgres
psql -c "CREATE DATABASE $1;"
psql -c "CREATE USER $1 WITH PASSWORD '$2';"
psql -c "GRANT ALL PRIVILEGES ON DATABASE $1 to $1;"

I probably suck bash scripting and I am trying to get better.

When you run the command

sudo -i -u postgres

a new shell is spawned. If you type exit at this point, this new shell will exit and your original shell will continue running the psql commands (but not as the postgres user).

You can do the following to fix this:

sudo -u postgres psql -c "CREATE DATABASE $1;"
sudo -u postgres psql -c "CREATE USER $1 WITH PASSWORD '$2';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $1 to $1;"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM