bashshellsudoheredocsu

Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically


I cannot figure out what's wrong with my bash script. When I run it in terminal, command by command run every command separately in terminal, it works.

#!/bin/bash    
sudo su <<EOF
mkdir /home/ubuntu/backup/
cp "$(ls -t /usr/lib/unifi/data/backup/autobackup | head -1)" /home/ubuntu/backup/
curl --insecure --user root:password -T "$(ls -t /home/ubuntu/backup/ | head -1)" sftp://vps2.duckdns.org:/root/backup.unf
EOF

However, when I run the above bash script, give me plenty of erros

bash -v test.sh
#!/bin/bash
sudo su <<EOF
mkdir /home/ubuntu/backup/
cp "$(ls -t /usr/lib/unifi/data/backup/autobackup | head -1)" /home/ubuntu/backup/
curl --insecure --user root:password -T "$(ls -t /home/ubuntu/backup/ | head -1)" sftp://vps2.duckdns.org:/root/backup.unf
EOF
ls: cannot access '/usr/lib/unifi/data/backup/autobackup': Permission denied
ls: cannot access '/home/ubuntu/backup/': No such file or directory
cp: cannot stat '': No such file or directory
curl: (78) Could not open remote file for reading: SFTP server: No such file

Any help will be very much appreciated!

TIA


Solution

  • It's trying to execute the command substitutions in the original shell, which runs with the regular user's permissions. They need to be executed by su. Quote the EOF token to prevent expansions in the here-document.

    sudo su <<'EOF'