What is the cleanest way to ssh and run multiple commands in Bash?

前端 未结 12 2244
礼貌的吻别
礼貌的吻别 2020-11-22 09:14

I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:

ssh blah_server "ls; pwd;"
         


        
12条回答
  •  故里飘歌
    2020-11-22 09:28

    How about a Bash Here Document:

    ssh otherhost << EOF
      ls some_folder; 
      ./someaction.sh 'some params'
      pwd
      ./some_other_action 'other params'
    EOF
    

    To avoid the problems mentioned by @Globalz in the comments, you may be able to (depending what you're doing on the remote site) get away with replacing the first line with

    ssh otherhost /bin/bash << EOF
    

    Note that you can do variable substitution in the Here document, but you may have to deal with quoting issues. For instance, if you quote the "limit string" (ie. EOF in the above), then you can't do variable substitutions. But without quoting the limit string, variables are substituted. For example, if you have defined $NAME above in your shell script, you could do

    ssh otherhost /bin/bash << EOF
    touch "/tmp/${NAME}"
    EOF
    

    and it would create a file on the destination otherhost with the name of whatever you'd assigned to $NAME. Other rules about shell script quoting also apply, but are too complicated to go into here.

提交回复
热议问题