Ashish
Ashish

Reputation: 1283

find command moves files but then files become inaccessible

I ran the following command in a parametrized version of a script:

Script1 as

Nooffiles=`find $1 -mmin $2 -type f -name "$3"|wc -l`
if test $Nooffiles -eq 0
then
exit 1
else
echo "Successful"
find $1 -mmin $2 -type f -name "$3" -exec mv '{}' $4 \;
fi

The script1 works fine. It moves the files from $1 directory to $4. But after it moves the files to the new directory, I have to run another script like this:

Script2 as

for name in `find $1 -type f -name "$2"`
do
filename=`ls $name|xargs -n1 basename`
line=`tail -1 $filename | sed "s/Z/Z|$filename/"`
echo $line >> $3;
echo $filename | xargs -n1 basename;
done

Here, script2 is reading from the directory where the files were moved to by the previous script, script1. They exists there in that directory since the previous moving script worked fine. 'ls' command displays them. But the above script2 says:

File.txt: No such file or directory

Despite ls shows them in the directory, I am getting an error message like this.

Please Help.

Upvotes: 0

Views: 641

Answers (1)

Jo So
Jo So

Reputation: 26531

Your script really is a mess and please be aware that you should NEVER parse filenames (like the output from ls, or find without -print0 option). See Bash Pitfalls #1.

Apart from that, I think the problem is that in your loop, you truncate the filenames output from find with basename, but then call tail with the base filename as argument, where the file really isn't located in the current folder.

I don't understand what you are doing there, but this is some more correct code that perhaps does next to what you want:

find "$1" -type f -name "$2" -print0 | while read -d '' name
do
    filename=`basename "$name"`
    tail -1 "$name" | sed "s/Z/Z|$filename/" >> "$3"
    echo "$filename"
done

But still, there are pitfalls in this script. It is likely to fail with queer filenames input from find. For example, if your filename contains characters that are special to sed. Or if at some point $filename is --help etc.etc.etc.

Upvotes: 1

Related Questions