I have to write a shell script that will monitor some folders given in the command and give a message if a certain file will be created inside them (the name of the file will be read from keyboard).
Can anyone tell me why is this not working?
#!/bin/sh
f=`read filename`
isIn=0
for dir in $*
do
if [ ! -d $dir ]
then
echo $dir is not a directory.
fi
for i in `find $dir -type f`
do
if [ $f=$i ]
then
echo The file $f already exists.
isIn=1
break
fi
done
if [ $isIn -eq 0 ]
then
sleep 20
isIn=0
for i in `find $dir -type f`
do
if [ $f=$i ]
then
echo The file was created\!
isIn=1
break
fi
done
fi
if [ $isIn -eq 0 ]
then
echo The file was not created\!
fi
done
The idea i used was that i take all the files from the directory and verify is the file isn't already there. If it is - show message and move to the next directory. If not then I 'wait'. if in the time i waited that certain file was created, it would have appeared in the list of all files, and i check for it.
My problem is that no matter what file I read from the keyboard, i would get the message "The file already exists." without telling me the name of the file.
f=`read filename`
with the correct usage read f
or read -p filename: f
. find $dir -type f
prints the full file name including the directory path. Since you want just the basename, replace both lines
for i in `find $dir -type f`
with
for i in `find $dir -type f -printf '%f\\n'`
Each operator and operand in [
]
must be a separate argument. Thus replace both lines
if [ $f=$i ]
with
if [ "$f" = $i ]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.