0

The below is not working when i run it as a script and doesn't even do an exit.

#!/bin/bash

sudo su - test
export PATH=$PATH:/opt/postgres/9.5/bin
export LD_LIBRARY_PATH=/opt/postgres/9.5/lib

BACKUP_RETENTION=$((7*24*60)) # 1 week
LOG_RETENTION=$((7*24*60)) # 1 week

BACKUP_DIR=/backup/data/pg_backup/
BACKUP_NAME=$BACKUP_DIR"test-db-`date +%Y-%m-%d-%H:%M`.zip"
KEY_AUTH=`cat /var/lib/test/.test_file`
LOG_DIR=/backup/log/
LOG_FILE=$LOG_DIR"test-db-`date +%Y-%m-%d-%H:%M`.log"

echo "Backup :: Script Start -- $(date +%Y-%m-%d_%H:%M)" >> $LOG_FILE
START_TIME=$(date +%s)

dump_name=$BACKUP_DIR$test_`date +%Y%m%d`.dump
pg_dump -c -p 11381 test -f "$dump_name" &&
zip --encrypt -P ${KEY_AUTH} ${BACKUP_NAME} "$dump_name" &&
rm "$dump_name"

# *** Deleting Backup Based on Retention *** #
find $BACKUP_DIR -name "*.zip" -mmin +${BACKUP_RETENTION} -delete

# *** Deleting Logs Based on Retention *** #
find $LOG_DIR -name "*.zip" -mmin +${LOG_RETENTION} -delete

END_TIME=$(date +%s)
ELAPSED_TIME=$(expr $END_TIME - $START_TIME)

echo "Backup :: Script End -- $(date +%Y-%m-%d_%H:%M)" >> $LOG_FILE
echo "Elapsed Time ::  $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) "  >> $LOG_FILE

exit 0
3
  • Can you remove the script line sudo su test and then run the script as root? sudo /path/myscript.sh or as user test sudo -u test /path/myscript.sh Commented Aug 23, 2017 at 13:39
  • "test" is db/app user. We login as privileged account then sudo to "test" to be able to run the script. We need to keep that within the script.. Commented Aug 23, 2017 at 14:05
  • You need to not keep the sudo su - test within the script. That is what is causing you problems. Commented Aug 23, 2017 at 14:27

2 Answers 2

4

The first line in this script launches a new shell under the test user ID, and waits for that shell to exit before running the first export command to modify the path. The script is doing exactly what you told it to do.

2
  • Hi John, We have to sudo that DB user then set PATHs and run backup due to application requirement and restrictions. I login to server as -- USER 1 then sudo su - (for root) -- then sudo su - test (which is in the script)...What changes i should do to be able to run the script in one go and then exit. Commented Aug 23, 2017 at 14:09
  • 1
    Do not run sudo su - test in that script. Instead, run sudo -u test <script>. That will run the script as the 'test' user. Commented Aug 23, 2017 at 14:26
0

As a follow-up to John's answer, you may change your sudo line to this:

if [ "$(id -un)" != "test" ]; then
    exec sudo -u test "$0" "$@"
    exit
fi

What this does is to re-execute the script with user test if this is not test that already executes it.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.