简体   繁体   中英

Multiple commands in sudo over ssh in shell script

My script is as below.

#!/bin/bash

version = 1.1

echo "Enter username"

read UserName

ssh -t $UserName@server bash -c " '

./runSomeScript

echo "Entering Sudo"

sudo -s -u user1 -c "cd random; ./randomscrip xx-$version-yy"

'"

But this is not working.

Basically i want to do a ssh to a account. And then runSomeScript Then do a sudo with user as user1 and then run commands cd random and ./randomscrip (with xx-Version-yy as argument) as the sudo user only. But the commands inside sudo are not working.

Your quoting is a little careless. You're using double-quotes for the first and third levels of quoting, and the shell can't tell one from the other. Do something like this instead:

sudoScript="cd random; ./randomscrip xx-${version}-yy"
sshScript='
  ./runSomeScript
  echo "Entering Sudo"
  sudo -s -u user1 bash -c '"'${sudoScript}'"'
'
ssh -t ${UserName}@server "${sshScript}"

But beware that if you embed any single-quotes, it will still go wrong unless you add a layer of shell-quoting.

Finally, remove the spaces around = when you assign to version .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM