Issue
I need to archive files with sys time on remote server but name of the file contains "SPACE" and special character. So below commands are not working.
FileName="BBB [email protected]"
ts=`date +"%m%d%Y%H%M%S"`
ssh remoteid@remoteserver "'mv /upload/hotfolders/in/"$FileName"
/upload/hotfolders/Archive/${FileName}_${ts}'"
But above command is failing with below error.
bash: mv /upload/hotfolders/in/BBB [email protected] /upload/hotfolders/Archive/BBB [email protected]_01282019050200: No
such file or directory
Solution
In the original provided code:
ssh remoteid@remoteserver 'cd /upload/hotfolders/; mv "$FileName"
/upload/hotfolders/Archive/"${FileName}_${ts}"'
the outermost '
are used on the local filesystem to keep all the commands as a single argument to ssh. However, this means that $FileName
, etc are not expanded locally! Instead, the unexpanded strings are passed verbatim to the remoteserver, where a shell is started to run the command. $FileName
, etc, are then expanded there. Because they are not defined there (probably), the expansion fails to produce anything useful.
In the amended version:
ssh remoteid@remoteserver "'mv /upload/hotfolders/in/"$FileName"
/upload/hotfolders/Archive/${FileName}_${ts}'"
there is a different problem. Here, the two sets of outermost "
allow the local system to expand the variables (although it may not be obvious that the first $FileName
is not actually inside "
). However, as the command that is passed is now wrapped in '
, the remote server will treat the entire string as a single word.
If we assume that FileName
and ts
will not contain shell-special characters (such as '
) then the fix is to wrap the command sequence in "
(so that it expands locally), and only wrap the variables in '
(so that the remote server treats the now-expanded strings as single words):
ssh remoteid@remoteserver "cd /upload/hotfolders/; mv '$FileName'
/upload/hotfolders/Archive/'${Filename}_${ts}'"
Answered By - jhnc