WRITELOOP

RUN A GROUP OF COMMANDS AS ANOTHER USER ON A BASH SHELL SCRIPT

2014 August 24

(This can be useful, for example, to run a command as another user on /etc/rc.local)

#!/bin/bash
su - sudouser <<'EOF'
cd /GPO/gpo_backend
/virtualenvs/gpo/bin/celery worker -B --app=gpo_backend.tasks -f /GPO/gpo_backend/log/celery.log -l info  --concurrency=1 &
EOF

This is using a feature called “Here Document”.

Here Documents are useful to do I/O redirection.

They are specially useful to “scriptize” a command list to some static interactive programs like “su” or “ssh” and quit.

It just won’t work so nice on programs that are require high interactivity (like ncdu, dialog programs, etc).

Another example:

  • Here we execute a df on a ssh session and come back to our terminal:

(we are using -t -t to avoid the message “Pseudo-terminal will not be allocated because stdin is not a terminal.”):

#!/bin/bash
ssh -t -t -p 22 user@192.168.0.1 <<'EOF'
# -onlcr: prevent the terminal from converting bare line feeds to carriage return/line feed pairs
# stty -echo -onlcr
df -m
ls -la
# stty echo onlcr
exit
EOF