Jaydeep Chaudhari
Jaydeep Chaudhari

Reputation: 430

Change User from bash script

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

Upvotes: 2

Views: 3363

Answers (1)

Laser
Laser

Reputation: 6960

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

Upvotes: 3

Related Questions