I’ve written a bash script with the following code:
#! /bin/bash
sc_files=`grep -l 'string' /home/test/dirpath/*`
sc_dir='/home/test/mvdir'
for i in $sc_files
do
"mv -f $i $sc_dir";
done
The output of the script produces:
./test.sh: line 6: mv -f /home/test/dirpath/test.txt /home/test/mvdir: No such file or directory
However, when this exact mv command is copied into the shell under the same user, it works and moves the file. The directories are named and have paths as in the script (as noted, the move works when the command is copied straight into an interactive shell), and my user has rwx permissions to both the source and destination directories. The files themselves are owned by a different user, but this shouldn’t prove an issue with write permissions to the directories. Any ideas would be much appreciated?
As the first answer points out, the quoting on your move command is incorrect. When you quote the entire command and its argument, bash sees the entire string with spaces included as the command.
There is another issue with the snippet you have provided. The for loop will not work properly if any of the files have spaces in the name. Even if you know that none of the files contain spaces, it is good practice to use a while loop instead.