2

I have a user "chad"

I am logging into linux machine with user "server"

I am creating a script and try to add below command

 sudo su -s /bin/bash chad

so I can get into user chad and execute rest of my commands from this script How do I do that?

Below Is My script

   #!/bin/bash

   exec /bin/su -s /bin/bash chad - << 'EOF'

   echo "pwd"
   pwd

   cd /home/chad/py2.0/test/py_it/


   echo "git branch"
   git branch



   read -p "Are you sure about branch? (yes/no)" reply

   choice=$(echo $reply|sed 's/\(.*\)/\L\1/')

   if [ "$choice" = 'yes' ] 
   then
   echo "Welcome you selected yes, wait for 3 seconds to get output";
   sleep 3;
   echo "git pull for py2.0";
   "git pull origin integration/py2.0";

   elif [ "$choice" = 'no'  ]
   then

   echo "You selected 'no', hence exiting in 3 seconds";
   sleep 3
   exit 0
   else
   echo "invalid answer, type yes or no";
   fi
   EOF

Below is Output

   git branch
  * integration/py2.0
   master
  invalid answer, type yes or no
2
  • Does that not work ? Commented Feb 10, 2016 at 10:15
  • If this doesnt work, did you try to export user into your script? export $USER=chad or you can use setenv Commented Feb 10, 2016 at 10:32

1 Answer 1

3

You have to add the following line in your script:
exec sudo -u chad /bin/sh - << 'EOF'

All commands after this line will be under chad user

Check it with this:

id
exec sudo -u chad /bin/sh - << 'EOF'
id
id
id
EOF
Sign up to request clarification or add additional context in comments.

13 Comments

not working .when i use exec sudo -u /bin/bash chad - << eof it changes the user but no other commands works in scrips
could you please give us more details
for example insert : id id id right after command
Script = #!/bin/bash exec su -s /bin/bash chad - << eof echo "pwd" cd cd chad_py2.0/chad_cloud/ echo "git branch" git branch read -p "Are you sure about branch? " -n 1 -r echo # (optional) move to a new line if [[ $REPLY =~ ^[Yy]$ ]] then echo "git pull for py2.0"
output = sudo ./test.sh ./test.sh: line 35: warning: here-document at line 3 delimited by end-of-file (wanted eof') pwd git branch * integration/py2.0 master bash: line 14: cho: command not found bash: line 15: conditional binary operator expected bash: line 15: syntax error near ^[Yy]$' bash: line 15: `if [[ =~ ^[Yy]$ ]]'
|

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.