Objective
You may often encounter this requirement at work, how do you check the existence of a file in the bash environment of a Unix-like system? Since there is a need, of course there is a solution, the shell of the test command, can be used to detect the type of file or compare the value is equal, the command can also be used to check whether the file exists.
The following command can be used to check:
TEST-E filename[-e filename] test-f filename[-f filename]
The following command uses the shell's conditional expression to determine whether the/etc/hosts file exists:
[-f/etc/hosts] && echo "Found" | | echo "Not Found"
The combo command outputs the following:
Found
The more common use is to place the test command in the IF: else.. The conditional expression of the fi condition and then writes the different branching logic in it
#!/bin/bashfile= "/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 a corresponding property, the following operator will return true:
-B file file exists and is block special-c file file exists and are 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-i D-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 have 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 have a size greater than Zero-s file file exists and is a Socke T-T FD File Descriptor FD is opened on a terminal-u file file exists and it Set-user-id bit is set-w file file exists and Write permission is granted-x the file file exists and execute (or search) permission is granted
The above command, copied from man Test.
The same method is used for the above notation:
If [operator FileName]then echo "Filename-found, take the some action here" else echo "Filename-not Found, take some Action Here "fi
Summarize
The above is the entire content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.