- Check if a directory exists in Linux or Unix shell
- How to check if a directory exists in Linux
- A note about symbolic links (symlink)
- Linux check if a directory exists and take some action
- Check if directory exists in bash and if not create it
- Using test command
- Getting help
- Conclusion
- How To Check If a Directory Exists In a Shell Script
- Checking If a Directory Exists In a Bash Shell Script
- Using if..else..if
- Shell script examples to see if a $ exists or not
- Summary
- Conclusion
- How to Check if File or Directory Exists in Bash Shell
- Check if file exists in bash script
- Check file exists in bash with test
- Check if file doesn’t exist in bash script
- Check if directory exists in bash script
- Check if directory doesn’t exist in bash
Check if a directory exists in Linux or Unix shell
How to check if a directory exists in Linux
- One can check if a directory exists in a Linux shell script using the following syntax:
[ -d «/path/dir/» ] && echo «Directory /path/dir/ exists.» - You can use ! to check if a directory does not exists on Unix:
[ ! -d «/dir1/» ] && echo «Directory /dir1/ DOES NOT exists.»
One can check if a directory exists in Linux script as follows:
Always enclose “$DIR” in double-quotes to deal with directories having white/black spaces in their names. For instance:
A note about symbolic links (symlink)
Directories with symbolic links need special consideration as follows using the -L switch:
Linux check if a directory exists and take some action
Here is a sample shell script to see if a folder exists or not in Linux:
Run it as follows:
./test.sh
./test.sh /tmp/
./test.sh /nixCraft
Check if directory exists in bash and if not create it
Here is a sample shell script to check if a directory doesn’t exist and create it as per our needs:
Make sure you always wrap shell variables such as $DIR in double quotes ( «$DIR» to avoid any surprises in your shell scripts:
Using test command
One can use the test command to check file types and compare values. For example, see if FILE exists and is a directory. The syntax is:
test -d «DIRECTORY» && echo «Found/Exists» || echo «Does not exist»
The test command is same as [ conditional expression. Hence, you can use the following syntax too:
[ -d «DIR» ] && echo «yes» || echo «noop»
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Getting help
Read bash shell man page by typing the following man command or visit online here:
man bash
help [
help [[
man test
Conclusion
This page explained various commands that can be used to check if a directory exists or not, within a shell script running on Linux or Unix-like systems. The -d DIR1 option returns true if DIR1 exists and is a directory. Similarly, the -L DIR1 option returns true if DIR1 found and is a symbolic links.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How To Check If a Directory Exists In a Shell Script
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash/Linux |
Est. reading time | 3 mintues |
Checking If a Directory Exists In a Bash Shell Script
The following version also check for symbolic link:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
The && is AND list operator. The syntax is:
foo && bar
The bar command is executed if, and only if, foo returns an exit status of zero (success). Similarly we have the || (OR) list and the syntax is:
cmd1 || cmd2
The cmd2 is executed if, and only if, cmd1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.
Using if..else..if
Finally, you can use the traditional if..else..fi bash syntax as follows:
Shell script examples to see if a $ exists or not
The following script also demos the use of readlink command to print value of a symbolic link or canonical file name.
Save and run it as follows:
$ chmod +x dirtest.bash
$ ./dirtest.bash
$ ./dirtest.bash /home/httpd
$ ./dirtest.bash /var/www
Sample outputs:
Fig.01: Shell script in action
Summary
Remember when we say “FILE”, it means directory too.
Use the following to check file/directory types and compare values:
- -L «FILE» : FILE exists and is a symbolic link (same as -h)
- -h «FILE» : FILE exists and is a symbolic link (same as -L)
- -d «FILE» : FILE exists and is a directory
- -w «FILE» : FILE exists and write permission is granted
- -x «FILE» : FILE exists and execute (or search) permission is granted
- -r «FILE» : FILE exists and read permission is granted
- -s «FILE» : FILE exists and has a size greater than zero
Conclusion
We learned how to check if a directory exists in a shell script using the test command and other methods under Linux/Unix bash. See the following resources for more information:
man test
man bash
man readlink
man stat
And:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I sometime use “[ -x $dir/. ]”, to check at the same time if directory exist and if the calling process has traverse rights on it.
“exits” “exits” “exits” all over the place where you had intended to write “exists”. you might want to change that.
Thanks for the heads up!
i love this one:
[[ -d dir ]] || mkdir dir
Isn’t that same as `mkdir -p dir`?
I really like this one for setting a variable to a file path only if it exists. From what I can tell, this is probably amongst the most efficient methods of doing such a task.
Lets assume we have the following:
/path/to/file
Using bash’s builtin “type” the “-P” does a PATH search, only printing if the filename is found within the path, irrespective of the executable state:
$ VAR1=$(PATH=/path/to type -P file)
$ echo $VAR1
/path/to/file
$
What is really neat about this is that we can use it to see if the file exists in several places, using the order of the temporary PATH to indicate preferences.
Let’s add a couple files for an example:
/path/to/file
/path/to/other/file
/other/directory/foo
Now if we want to set “file” as a variable, and know it should be in one of three places, we can do…
$ VAR2=$(PATH=/path/to/other:/path/to:/other/directory type -P file)
$ echo $VAR2
/path/to/other/file
$
But what if /path/to takes precedence? An example is any program that gives configs in /etc priority over /usr/lib if identically named (ie. systemd, modprobe.d, etc.). We can use the PATH order to match by level of significance…
$ VAR3=$(PATH=/path/to:/path/to/other:/other/directory type -P file)
$ echo $VAR3
/path/to/file
$
Bash’s builtin “type” is quite nice in that upon failure, it prints nothing. So you don’t even need to throw out stderr with “2>/dev/null”!
$ VAR4=$(/path/to:/path/to/other:/other/directory type -P baz)
$ echo $VAR4
Even if you did “echo $FARTBRAINS” it still creates a nice \n for you, even if you’ve never even remotely thought about using that variable name. So VAR4 is essentially unset. Neat!
Usually I’m a zsh user. Zsh’s “whence” and “which” come closest, but cannot search beyond executables and print a short fail message (that I’d otherwise not mind). I’m sure other shells might behave similarly, but those are the two I’ve tested. I script with bash anyway.
Unfortunately, I have not come up with a way to do directories in a similar manner. I really searched through the bash shell builtin documentation and google-fu’ed the best I could, but I cannot figure anything out that is that efficient.
Hopefully someone smarter than me can prove there is a way. I don’t know if I’ll ever check this page again… and don’t know why I just put so much work into this comment. But I hope you enjoyed!
Hi, there is an error in your example, if the dir does not exist at all (and no link) the example below still prints the “Error……” (the OR part)
Yep, I concur, it’s incorrect/incomplete in that sense. I’ve made a quick alteration that I believe works with a bit more clarity:
Slight improvement for stdin / stdout clarity:
[ -d «$aptLocalRepo» ] && [ ! -L «$aptLocalRepo» ] && printf «Dir:\nDirectory exists: $aptLocalRepo\n» || \
[ -L $aptLocalRepo ] && printf «Symlink:\n$aptLocalRepo\nPoints to:\n$(readlink -f $aptLocalRepo)\n» || \
printf «Dir:\nDirectory does not exist: $aptLocalRepo\n»
Second example is a typo – you need a space between the opening bracket and the bang, like this
The current code would cause “ bash: [!: command not found ” error message
Источник
How to Check if File or Directory Exists in Bash Shell
If you are working on a Bash script that interacts with files and directories, you might encounter a situation where you need to make sure that the file or directory exists. This helps avoiding possible errors for performing certain actions on a file that doesn’t exist.
In this tutorial, I’ll show you a couple of ways to check if file or directory exists in bash script or not. Let’s start with file first.
Check if file exists in bash script
The idea here is to use the -f operator that returns true only when it is a regular file (not directory).
Let’s say you want to check if file /home/user/my_file exists or not. Here’s how you can check with square brackets
But you won’t always get the file name before hand, will you? You can have it in a variable and if that’s the case, you can use it in this fashion.
Basically, what matters is the condition you use in the if command. It’s up to you how you want to use the if statement.
For example, you can write it with two square brackets, keep ‘then’ in the same line as ‘if’ with the help of semicolon like this:
or put the entire statement together like this:
Check file exists in bash with test
You can also use test in bash to see if file exists or not. It’s pretty much the same thing only that you don’t use the square brackets in the if statement:
You can also use the above code in single line like this:
Check if file doesn’t exist in bash script
What if it’s the other way round and you want to check if file does not exist in bash? You can use pretty much the same code as above by using the negation operator:
Now that you know how to deal with files, let’s move on to directories.
Check if directory exists in bash script
The code for checking directory is the same as the one you saw in the previous section. The only difference is that you’ll be using -d instead of -f. -d returns true only for directories.
You can also use test here:
Check if directory doesn’t exist in bash
You can use the negation again to check if directory doesn’t exist:
That’s it. That’s all you need to do for checking if a directory of file exists in bash shell or not.
I hope you find this bash tip useful. If you have any questions or suggestions, please feel free to leave a comment below.
Источник