简体   繁体   中英

bash: grep only returns “Is a directory” when searching for a file that exists

Up until recently, I was able to have a script make sure a certain file exists within a certain directory before continuing.

Now, the script either does not find the file or, when grep works, just returns "grep: /Users/user/Downloads: Is a directory" when finished."

The file is exists in the directory, but grep doesn't want to interact with it anymore. This is the sort of thing I'm working with:

if grep -q 'file.bin' ~/Downloads; then echo "It works!" exit 1 fi

Any advice would be appreciated. Thanks.

You are asking grep to search for a string ( file.bin ) in a file called ~/Downloads ...which is a directory. So the error you are seeing is accurate; grep only operates on files, not on directories.

If you want to see if a file exists, you probably just want to use the standard shell tests for files:

if [ -f ~/Downloads/file.bin ]; then
    echo "It exists!"
fi

You would use grep to see if a string exists in a file:

if grep -q "a string" ~/Downloads/file.bin; then
    echo "The file contains the string"
fi

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM