I am writing a shell script and I need to SSH into a server, perform some actions, and then exit.
To do this, I am using code such as below:
ssh -t username@server '
cd uploads/; \
tar -xvzf torrent.tar.gz; \
'
However, I need to use a variable like so:
DIR="uploads/";
ssh -t username@server '
cd $DIR; \
tar -xvzf torrent.tar.gz; \
'
This doesn’t seem to work because obviously the cd isn’t being executed until the SSH connection is made, and by then there is no $DIR variable (my guess). However, is there any way I could use a variable?
Perhaps a better question is, is there a better way I could lay out my script to perform actions once the SSH connection is made? I am having to be careful, escaping apostrophes, and at one point I am actually SSHing to another server from inside an SSH connection. This is ugly code!
Edit: Just read that if I use ” instead of ‘, the variable will work. However my question still stands about formatting?
Use double quotes to allow expansion. e.g. try this:
vs
and note the result.
It’s worth wrapping this in a shell script thus:
and the -x will output shell expansions etc. It makes life very easy for debugging.
Rather than using the above means to feed in commands, you can use a heredoc. e.g.
will execute ‘ls’ on the remote host.