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
By default
ssh
reads from stdin which is your input file andssh
consumes the rest of the file and yourfor
loop terminates.To prevent this, pass the
-n
option to your ssh command to make it read from/dev/null
instead ofstdin
.From ssh man page:
See this thread for more.