Search code examples
bashsshrm

Removing a remote file through ssh stops the while loop the command is in?


I have this script that lists files having been modified more than 10minutes ago on a remote disk, retrieve them locally, and then, is supposed to delete them on remote. The script works when I don't remove the files. As soon as I add the line to remove the files, the loop is only processed once (only one file is successfully copied, and I have the message confirming it is in local disk), and then the loop stops without any error message. Please, any idea why?

#!/bin/bash

S_ACCOUNTS=('yohplala')
RMT_IP='88.214.320.588'
LOC_PATH_DATA='../data/cs_remote/'
MOD_TIME='+10'                      # Last modification time, in minutes

# List, copy, delete files.
for serv_account in "${S_ACCOUNTS[@]}"; do
    while IFS= read -r -d $'\0' file; do
        scp -i ~/.ssh/id_rsa root@$RMT_IP:"$file" "$LOC_PATH_DATA""$serv_account"
        if test -f "$LOC_PATH_DATA""$serv_account"'/'"$(basename "$file")"; then
            echo "$(basename "$file")"' successfully copied.'
            ssh root@$RMT_IP "rm $file"                          # <= troublesome line here
        fi
    done < <(ssh root@$RMT_IP "find "/root/test" -maxdepth 1 -type f -mmin $MOD_TIME -print0")
done


Solution

  • By default ssh reads from stdin which is your input file and ssh consumes the rest of the file and your for loop terminates.

    To prevent this, pass the -n option to your ssh command to make it read from /dev/null instead of stdin.

    From ssh man page:

    -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)

    See this thread for more.