What is the cleanest way to ssh and run multiple commands in Bash?
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 << EOFtouch "/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.