I've been trying to update my backup script such that it saves data on a remote server instead of on a local disk.

I have succeeded in converting the entire script but the last part in which I remove all the files from the directory except the n newest.

In order to debug and pinpoint the cause I have temporarily removed all variables.

The command I wish to run on my remote machine is the following:

ls -tr1 /mnt/backup1tb/testarossa/test | tail -n +5 | xargs -d '\n' rm -f

When I execute this command it does what I expect it to do. It leaves the newest 4 files (or directories) and removes the rest.

To execute it over SSH I have the following line in my script:

foo=`ssh $remoteuser@$remoteaddr ls -tr1 /mnt/backup1tb/testarossa/test | tail -n +5 | xargs -d '\n' rm -f`

I have tried removing the last part, the | xargs -d '\n' rm -f and that indeed returns the directory listing of files that need removal. Howeve, adding the xarg part does not remove the files.

  • 3
    anything past the pipe is done on your local machine, i.e. it's the local tail command that is run if you don't put it in quotes: ssh user@host "complex | command | pipe". – Fiximan Aug 23 '15 at 15:32

You need to enclose the remote command in quotes to execute it all on remote server, otherwise you run everything after pipe on local host, which is not what you want (as described in comments):

foo=`ssh $remoteuser@$remoteaddr "ls -tr1 /mnt/backup1tb/testarossa/test | tail -n +5 | xargs -d '\n' rm -f"`

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.