I have an if
statement to calculate files and delete all except the latest three files. But I want to run this command remotely. How can I combine ssh
with an if
condition?
I tried this but no success.
#!/bin/bash
ssh -t test@192.168.94.139 "cd /var/www/test.com/backup ;
if [ $(ls | wc -l) -lt 3 ]
then
echo "Less"
else [ $(ls -t *.tgz|awk 'NR >3'|xargs rm -f) ]
echo "deleted"
fi"
The error I got:
ls: cannot access *.tgz: No such file or directory
Best Answer
NOTE: there are in fact two layers to the question here. One is 'I want to execute a non-trivial task on a remote server accessible via SSH'. The other is 'I'm trying to pass a complex string to a command, and the argument ends up being different from what I intended.' I'm answering the low-level question without discussing whether the approach used is "right" (convenient, non-error-prone, secure etc.) for solving the high-level one. As indicated by the other answers and comments, it quite possibly isn't.
Your command line is mostly right; you only have to change the quoting a bit.
The main problem is that double-quoted strings are expanded by your local shell, and so the
$(...)
parts will be evaluated on your local system. To pass them over to the remote system, you have to enclose the script in single quotes.You also have some embedded quotation marks. In your original script, there are the arguments for the two
echo
s; if you change the outer quotation to single quotes, it will be the awk script. These effecitvely result in the quotation marks being omitted, which doesn't bother theecho
s, but it will mess up the awk script, as the greater-than sign will become output redirection. So after you change the outer quotation marks to single quotes, change those to double quotes.This is your script with the quoting fixed. The script may have other issues, I just fixed the syntax.