I have 2 questions about that topic:
I need to search for a file c.txt in a directory, and I know that if [[ -f c.txt ]]
will search for it at the current directory the script is running, but How do I do I search in a certain directory for example dir1 , the file a.txt?
In this way it will also search in all the sub directories? For example: if dir1 doesnt contain a.txt but it has dir2 that contains c.txt, will I get true or false?
This will find all files named a.txt
find -type f -name a.txt
This will find all files named like [something].txt
find -type f -name *.txt
If you want the return value and not the output of found files, use
find -type f -name *.txt >/dev/null
[[ $? == 0 ]] && echo "FILE FOUND" || echo "FILE NOT FOUND"
You can do more testing and even have more fun using find -exec... For more info use
man find
EDIT: When you are NOT allowed to use find
, use this
to test is a.txt exist in dir1
[[ -f "/full/path/to/file/dir1/a.txt" ]]
and to test if a.txt or c.txt exist in dir1 or dir2
[[ -f "/full/path/to/file/dir1/a.txt" || -f "/full/path/to/file/dir2/c.txt" ]] && echo "a.txt or c.txt exist!" || echo "neither a.txt nor c.txt exist"
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.