从bash脚本更改用户

时间:2016-02-10 10:14:31

标签: bash shell

我有一个用户“chad”

我使用用户“server”登录linux机器

我正在创建一个脚本并尝试添加以下命令

 sudo su -s /bin/bash chad

所以我可以进入用户chad并从这个脚本执行其余的命令 我该怎么做?

以下是我的脚本

   #!/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

以下是输出

   git branch
  * integration/py2.0
   master
  invalid answer, type yes or no

1 个答案:

答案 0 :(得分:3)

您必须在脚本中添加以下行:
exec sudo -u chad /bin/sh - << 'EOF'

此行之后的所有命令都将在chad user

用这个检查:

id
exec sudo -u chad /bin/sh - << 'EOF'
id
id
id
EOF