In the first version of the script, your local bash interpreter is removing the quotes before ssh
is run, so
ssh $SSH_HOST "rm -rf $DIR_REMOTE"
and
ssh $SSH_HOST rm -rf $DIR_REMOTE
do exactly the same thing -- you're passing rm -rf ~/directory
to $SSH_HOST
via ssh.
When you run
CMD="ssh $SSH_HOST \"rm -rf $DIR_REMOTE\""
echo "$CMD"
$CMD
the bash interpreter is removing the first set of quotes, and you're passing the quoted string "rm -rf ~/directory"
to $SSH_HOST
via ssh. The remote shell (in this case zsh
) is trying to execute the file "rm -rf ~/directory"
, and cannot, so it's throwing an error message.
If you leave off the inner quotes:
CMD="ssh $SSH_HOST rm -rf $DIR_REMOTE"
echo "$CMD"
$CMD
You will be sending the unquoted string rm -rf ~/directory
via ssh, and zsh
will interpret it correctly.
Edit: As mentioned in the comments, running code from variables, while possible, is brittle and likely to be insecure; as such, it's considered bad practice. Variables are for data, functions are for code.
As such, you're much better off writing a function:
#!/bin/bash
remove_remote_dir() {
local SSH_HOST=$1
local DIR_REMOTE=$2
ssh $SSH_HOST "rm -rf $DIR_REMOTE"
}
remove_remote_dir hostname '~/directory'