Preface
You may often encounter such needs when working. In the Bash environment of a Unix-like system, how to check whether a file exists? Since there is a need, of course there is a solution. The test command in the Shell can be used to detect the type of the file or compare whether the values are equal. This command can also be used to check whether the file exists.
You can use the following command to check:
test -e filename [ -e filename ] test -f filename [ -f filename ]
The following command uses Shell’s conditional expression to determine /etc/ Whether the hosts file exists:
[ -f /etc/hosts ] && echo "Found" || echo "Not found"
This combined command will output the following:
Found
The more common usage is to place the test command in the conditional expression of if..else..fi conditional judgment, and then write different branch logic in it
#!/bin/bash file="/etc/hosts" if [ -f "$file" ] then echo "$file found." else echo "$file not found." fi
Related operators for detecting file attributes
If the file exists and has corresponding attributes, the following operators will return true:
-b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and read permission is granted -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and write permission is granted -x FILE FILE exists and execute (or search) permission is granted
The above commands are copied from man test.
The method of using the above symbols is exactly the same:
if [ operator FileName ] then echo "FileName - Found, take some action here" else echo "FileName - Not found, take some action here" fi
##SummaryThe above is the entire content of this article, I hope The content of this article can be of certain help to everyone's study or work. If you have any questions, you can leave a message to communicate. For more related articles on how to use Bash Shell to check whether a file exists, please pay attention to the PHP Chinese website!