- 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
- Linux / UNIX: Find Out If a Directory Exists or Not
- General syntax to see if a directory exists or not
- Find out if /tmp directory exists or not
- Sample Shell Script to gives message if directory exists
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
Источник
Linux / UNIX: Find Out If a Directory Exists or Not
I’ve already written a small tutorial about finding out if a file exists or not under Linux / UNIX bash shell. However, couple of our regular readers like to know more about a directory checking using if and test shell command.
General syntax to see if a directory exists or not
[ -d directory ]
OR
test directory
See if a directory exists or not with NOT operator:
[ ! -d directory ]
OR
! test directory
Find out if /tmp directory exists or not
Type the following command:
$ [ ! -d /tmp ] && echo ‘Directory /tmp not found’
OR
$ [ -d /tmp ] && echo ‘Directory found’ || echo ‘Directory /tmp not found’
- 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 ➔
Sample Shell Script to gives message if directory exists
Here is a sample shell script:
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.
We can do the same thing to check a file exist or not by modifying the “if” loop like the following.
if [ $# -ne 1 ]
then
echo “Usage: $0
exit 1
fi
if [ -f “$FILE” ]
then
echo “$FILE file exists!”
else
echo “$FILE file not found!”
fi
u can use test -f to check whether filename exists or not
u can use test -d to check whether directoryname exists or not
Returns “zero” if exists and “one” if doesn’t exist.
# [ -f /path/to/dir/file_name ] && echo “File Found” || echo “File not found”
i need to print the file names of all files having .txt extension of a given directory after converting to uppercase letters. The input (directory name) should be given as command line argument. The script will also check whether sufficient arguments are passed or not and whether the argument is a directory or not
i tried using this code
if [ -f $filename ]
tr “[a-z]” “[A-Z]” Qrious Nov 21, 2012 @ 11:46
Helps me a lot !
Thanks for posting..
ls -d /some/carzy/directory/does/it/exist
ls: cannot access /some/carzy/directory/does/it/exist: No such file or directory
Источник