1
Ubuntu 18.04

I have one shell script: doit.sh that copies a shell script to another user's home folder, and then tries to run it. I tried multiple combinations, but it's not working.

doit.sh:

#!/usr/bin/env bash
sudo mv testsh.sh /home/test3
sudo chown test3:test3 /home/test3/testsh.sh
sudo -i -u test3 bash << EOF
testsh='testsh.sh'
exec $testsh
EOF

testsh.sh:

#!/bin/bash
echo "export RAILS_ENV='rails_env'" |  tee test3.4 >/dev/null

testsh.sh was moved to /home/test3, but the test3.4 file was not created in /home/test3 and I am not getting any error messages. Any idea if this can be done?

1 Answer 1

2

The problem is that $testsh is being expanded by the original shell, not the shell run by sudo. You need quote the EOF token to prevent variable expansion in the here-doc.

sudo -i -u test3 bash << 'EOF'
testsh='testsh.sh'
exec $testsh
EOF

But I'm not sure why you need that variable, you can just do:

sudo -i -u test3 /home/test3/testsh.sh
Sign up to request clarification or add additional context in comments.

12 Comments

I did not realize I can simply execute that shell script as the other user. Your solution is missing the bash command to execute the shell. Without it, I get an error message. This solves the problem I'm having
There's no need for the bash command, that's done automatically by #!/bin/bash in the script.
Make sure you chmod 755 testsh.sh
I kept getting an error message: testsh.sh: command not found. When I added bash, it worked. This is on Ubuntu 18.04. I checked and the x flag was set for all
Make sure testsh.sh has Unix newlines, not Windows newlines.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.