PDA

View Full Version : [SOLVED] how to find a file in shell script



mdpalow
November 8th, 2007, 03:44 AM
.

kast
November 8th, 2007, 04:13 AM
if [ -f /home/$USER/*/grep-warn ] # that's just a file on my desktop
then
echo "found it"
else
echo "cant find it"
fi


That works for me, and if I put a fake file in it will echo the "cant find"

mdpalow
November 8th, 2007, 06:07 AM
.

mdpalow
November 8th, 2007, 06:31 AM
.

yabbadabbadont
November 8th, 2007, 06:37 AM
man find
:D

There is a bash wildcard technique using {,/OptionalDirName} but I've never messed with it myself. You should be able to use the return code from the find command with multiple search paths to do what you need.

mdpalow
November 8th, 2007, 07:01 AM
thanks...

I need to find the file using ' if ' because there is a condition I want to add IF it's found.

ghostdog74
November 8th, 2007, 07:35 AM
not really sure what you want, however, if you want to find a specific file,


# find /home/$USER -user $USER -type f -name "specific_file.txt"

depend on whether you want to check ownership, you can remove the -user flag

yabbadabbadont
November 8th, 2007, 08:22 AM
/home/daffy $ l temp/
total 4
-rw-r--r-- 1 daffy users 1190 2007-11-02 02:09 stuff.txt
/home/daffy $ MYFILELIST=$(find . -name stuff.txt 2>/dev/null)
/home/daffy $ echo $MYFILELIST
./temp/stuff.txt
/home/daffy $ MYFILELIST=$(find . -name stuff.notfound 2>/dev/null)
/home/daffy $ echo $MYFILELIST

/home/daffy $ if [ -z "$MYFILELIST" ]
> then
> echo "not found"
> else
> echo "found"
> fi
not found
/home/daffy $ MYFILELIST=$(find . -name stuff.txt 2>/dev/null)
/home/daffy $ echo $MYFILELIST
./temp/stuff.txt
/home/daffy $ if [ -z "$MYFILELIST" ]; then echo "not found"; else echo "found"; fi
found

The rest is left as an exercise for the student. :D

mdpalow
November 8th, 2007, 08:28 AM
thanks very much to all... I got it..

synss
November 8th, 2007, 10:40 AM
thanks...

I need to find the file using ' if ' because there is a condition I want to add IF it's found.

I know it says solved but...

If you want to do something on the file that "find" found (example with echo, but can be replaced by any command)


find . -name "filename" -exec echo '{}' " found" \;

what is between -exec and \; will be run; the '{}' will be replaced by whatever has been found.

Please, have a look at

man find