


How to check if a file or directory exists in Bash
Many times, when writing a Shell script, you need to perform operations based on whether the file exists. So how to check if the file exists? The following article will show you how to use the test command to check whether a file or directory exists in Bash. I hope it will be helpful to you.
test command
In Bash, you can use the test command to check whether a file exists and determine whether the file exists type.
The test command takes one of the following syntax forms:
test EXPRESSION [ EXPRESSION ] [[ EXPRESSION ]]
If you want your script to be portable, you should prefer using the old test [ command which is available on all POSIX shells. A new upgraded version of the test command [[ (double brackets) is supported on most modern systems using bash, zsh, and ksh as the default shell.
File operators of the test command
The test command includes the following File operators, allowing testing of specific types of files:
● -b FILE: True if FILE exists and is a block special file.
● -c FILE: True if FILE exists and is a special character file.
● -d FILE: True if FILE exists and is a directory.
● -e FILE: True if FILE exists and is a file, regardless of type (node, directory, socket, etc.).
● -f FILE: True if FILE exists and is a regular file (not a directory or device).
● -G FILE: True if FILE exists and has the same group as the user running the command.
● -h FILE: True if FILE exists and is a symbolic link.
● -g FILE: True if FILE exists and the set-group-id (sgid) flag is set.
● -k FILE: True if FILE exists and the sticky bit flag is set.
● -L FILE: True if FILE exists and is a symbolic link.
● -O FILE: True if FILE exists and is owned by the user running the command.
● -p FILE: True if FILE exists and is a pipe.
● -r FILE: True if FILE exists and is readable.
● -S FILE: True if FILE exists and is a socket.
● -s FILE: True if FILE exists and has a non-zero size.
● -u FILE: True if exists and set-user-id (suid) flags are set.
● -w FILE: True if FILE exists and is writable.
● -x FILE: True if FILE exists and is executable.
How to check if a file exists?
When checking whether a file exists, the most commonly used FILE operators are -e and -f. The first operator will check if the file exists regardless of file type; the second operator will only return true if the file is a regular file (not a directory or device).
When checking whether a file exists, the most readable option is to use the test command in combination with an if statement. Any of the following code snippets will check if the /etc/resolv.conf file exists:
FILE=/etc/resolv.conf if test -f "$FILE"; then echo "$FILE exist" fi
FILE=/etc/resolv.conf if [ -f "$FILE" ]; then echo "$FILE exist" fi
FILE=/etc/resolv.conf if [[ -f "$FILE" ]]; then echo "$FILE exist" fi
If you want to perform different actions based on whether the file exists, just use an if/then structure:
FILE=/etc/resolv.conf if [ -f "$FILE" ]; then echo "$FILE exist" else echo "$FILE does not exist" fi
Note: Always use double quotes to avoid problems when working with files that contain spaces in their names.
You can also use the test command without an if statement. The command after the && operator will only be executed if the exit status of the test command is true.
test -f /etc/resolv.conf && echo "$FILE exist"
[ -f /etc/resolv.conf ] && echo "$FILE exist"
[[ -f /etc/resolv.conf ] && echo "$FILE exist"
If you want to run a series of commands after the && operator, just enclose the commands with ";" Or in curly brackets separated by "&&".
[ -f /etc/resolv.conf ] && { echo "$FILE exist"; cp "$FILE" /tmp/; }
Contrary to &, the statement following the || operator is only executed when the exit status of the test command is false.
[ -f /etc/resolv.conf ] && echo "$FILE exist" || echo "$FILE does not exist"
How to check if a directory exists?
-d operator allows testing whether a file is a directory.
For example, to check whether the /etc/docker directory exists, you need to use:
FILE=/etc/docker if [ -d "$FILE" ]; then echo "$FILE is a directory" fi
[ -d /etc/docker ] && echo "$FILE is a directory"
Similarly, you can also use double brackets [[ instead of a single bracket [.
How to check if a file does not exist?
Similar to many other languages, it can be used! (exclamation point) logical NOT operator to negate the test expression:
FILE=/etc/docker if [ ! -f "$FILE" ]; then echo "$FILE exist and it is a directory" fi
Same as above:
[ ! -f /etc/docker ] || echo "$FILE does not exist"
How to check if multiple files exist?
If multiple files exist, you can use -a (or &&with[]) to test instead of using complex nested if/else constructs:
FILE=/etc/docker if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then echo "$FILE is a directory" fi
FILE=/etc/docker if [ -f /etc/resolv.conf && -f /etc/hosts ]; then echo "$FILE is a directory" fi
Equivalent variant without IF statement:
[ -f /etc/resolv.conf -a -f /etc/hosts ] && echo "both files exist"
[[ -f /etc/resolv.conf && -f /etc/hosts ]] && echo "both files exist"
Recommended related video tutorials: "Linux Tutorial"
The above is the entire content of this article, I hope it can help Everyone’s learning helps. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to check if a file or directory exists in Bash. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

The five basic components of the Linux system are: 1. Kernel, 2. System library, 3. System utilities, 4. Graphical user interface, 5. Applications. The kernel manages hardware resources, the system library provides precompiled functions, system utilities are used for system management, the GUI provides visual interaction, and applications use these components to implement functions.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

To view the Git repository address, perform the following steps: 1. Open the command line and navigate to the repository directory; 2. Run the "git remote -v" command; 3. View the repository name in the output and its corresponding address.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
