I am trying to copy all the content from a remote folder into my local machine, via bash script:
#!/usr/bin/env bash
REMOTE_SOURCE="/absolute/path/to/source/data"
TARGET="/absolute/local/path/to/target"
SSH="ssh myuser@myhost"
cd $TARGET
echo $PWD
TRANSFER="$SSH -- 'cd $REMOTE_SOURCE; tar cz ./' | tar xz"
echo $TRANSFER
$TRANSFER
Running the script, with the transfer command stored inside a variable fails with:
bash: cd /absolute/path/to/source/data; tar cz ./: No such file or directory
While it works correctly when copying the output from echo $TRANSFER
and running directly into the shell:
ssh myuser@myhost -- 'cd /absolute/path/to/source/data; tar cz ./' | tar xz
Note:
- The remote folder of course exists, so the reported error is confusing and doesn't help me to understand what to fix.
- I get the error also removing the
tar cz ./
part and leaving just thecd
command.
UPDATE:
Removing the '
-quoting makes the commands work.
But how to pipe the ssh
result into tar xz
then?
Solution:
The script should quote as less as possible, avoiding too much variable expansion magic:
echo "$SSH -- \"cd $REMOTE_DATA; tar cz ./ \" | tar xz"
$SSH -- "cd $REMOTE_DATA; tar cz ./" | tar xz