- 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 a directory exists in Linux command line?
- 7 Answers 7
- Related
- Hot Network Questions
- Subscribe to RSS
- C++ — Determining if directory (not a file) exists in Linux [duplicate]
- 6 Answers 6
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 a directory exists in Linux command line?
How to check if a directory exists in Linux command line?
Solution: [ -d ¨a¨ ]&&echo ¨exists¨||echo ¨not exists¨
7 Answers 7
Assuming your shell is BASH:
The canonical way is to use the test(1) utility:
where path is the pathname of the directory you want to check for.
For example:
[ -d «YOUR_DIR» ] && echo «is a dir»
[ -d / ] && echo «root dir «
will output: root dir .
To check if a directory exists in a shell script you can use the following:
to check the opposite , add ! before the -d ->[ ! -d . ]
I usually just ls it:
If it exists, you’ll see its contents, if it doesn’t exist you’ll see an error like this:
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
C++ — Determining if directory (not a file) exists in Linux [duplicate]
How would I determine if a directory (not a file) existed using C++ in Linux? I tried using the stat() function but it returned positive when a file was found. I only want to find if the inputted string is a directory, not something else.
6 Answers 6
According to man(2) stat you can use the S_ISDIR macro on the st_mode field:
Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.
how about something i found here
If you can check out the boost filesystem library. It’s a great way to deal with this kind of problems in a generic and portable manner.
In this case it would suffice to use:
The way I understand your question is this: you have a path, say, /foo/bar/baz (baz is a file) and you want to know whether /foo/bar exists. If so, the solution looks something like this (untested):
In C++17**, std::filesystem provides two variants to determine the existence of a path:
- is_directory() determines, if a path is a directory and does exist in the actual filesystem
- exists() just determines, if the path exists in the actual filesystem (not checking, if it is a directory)
Example (without error handling):
Both functions throw filesystem_error in case of errors. If you want to avoid catching exceptions, use the overloaded variants with std::error_code as second parameter.
If you want to find out whether a directory exists because you want to do something with it if it does (create a file/directory inside, scan its contents, etc) you should just go ahead and do whatever you want to do, then check whether it failed, and if so, report strerror(errno) to the user. This is a general principle of programming under Unix: don’t try to figure out whether the thing you want to do will work. Attempt it, then see if it failed.
If you want to behave specially if whatever-it-was failed because a directory didn’t exist (for instance, if you want to create a file and all necessary containing directories) you check for errno == ENOENT after open fails.
I see that one responder has recommended the use of boost::filesystem . I would like to endorse this recommendation, but sadly I cannot, because boost::filesystem is not header-only, and all of Boost’s non-header-only modules have a horrible track record of causing mysterious breakage if you upgrade the shared library without recompiling the app, or even if you just didn’t manage to compile your app with exactly the same flags used to compile the shared library. The maintenance grief is just not worth it.
Источник