Linux if path exists

Check if a directory exists in Linux or Unix shell

How to check if a directory exists in Linux

  1. One can check if a directory exists in a Linux shell script using the following syntax:
    [ -d «/path/dir/» ] && echo «Directory /path/dir/ exists.»
  2. 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:

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:

  1. -L «FILE» : FILE exists and is a symbolic link (same as -h)
  2. -h «FILE» : FILE exists and is a symbolic link (same as -L)
  3. -d «FILE» : FILE exists and is a directory
  4. -w «FILE» : FILE exists and write permission is granted
  5. -x «FILE» : FILE exists and execute (or search) permission is granted
  6. -r «FILE» : FILE exists and read permission is granted
  7. -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 File Exists With Conditional Expressions in a Bash Shell

W ith the help of BASH shell and IF command, it is possible to find out if a file exists or not on the filesystem. A conditional expression (also know as “evaluating expressions”) can be used by [[ compound command and the test ( [ ) builtin commands to test file attributes and perform string and arithmetic comparisons.


You can easily find out if a regular file does or does not exist in Bash shell under macOS, Linux, FreeBSD, and Unix-like operating system. You can use [ expression ] , [[ expression ]] , test expression , or if [ expression ]; then . fi in bash shell along with a ! operator. Let us see various ways to find out if a file exists or not in bash shell.

Syntax to find out if file exists with conditional expressions in a Bash Shell

The general syntax is as follows:
[ parameter FILE ]
OR
test parameter FILE
OR
[[ parameter FILE ]]
Where parameter can be any one of the following:

  • -e : Returns true value if file exists.
  • -f : Return true value if file exists and regular file.
  • -r : Return true value if file exists and is readable.
  • -w : Return true value if file exists and is writable.
  • -x : Return true value if file exists and is executable.
  • -d : Return true value if exists and is a directory.

Please note that the [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells. Let us see some examples.

Find out if file /etc/passwd file exist or not

Type the following commands:
$ [ -f /etc/passwd ] && echo «File exist» || echo «File does not exist»
$ [ -f /tmp/fileonetwo ] && echo «File exist» || echo «File does not exist»

How can I tell if a regular file named /etc/foo does not exist in Bash?

You can use ! operator as follows:
[ ! -f /etc/foo ] && echo «File does not exist» Exists
OR

[[ example

Enter the following commands at the shell prompt:
$ [[ -f /etc/passwd ]] && echo «File exist» || echo «File does not exist»
$ [[ -f /tmp/fileonetwo ]] && echo «File exist» || echo «File does not exist»

Find out if directory /var/logs exist or not

Type the following commands:
$ [ -d /var/logs ] && echo «Directory exist» || echo «Directory does not exist»
$ [ -d /dumper/fack ] && echo «Directory exist» || echo «Directory does not exist»

[[ example

$ [[ -d /var/logs ]] && echo «Directory exist» || echo «Directory does not exist»
$ [[ -d /dumper/fake ]] && echo «Directory exist» || echo «Directory does not exist»

Are two files are the same?

Use the -ef primitive with the [[ new test command:

How to check if a file exists in a shell script

You can use conditional expressions in a shell script:

Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf
To check if a file exists in a shell script regardless of type, use the -e option:

You can use this technique to verify that backup directory or backup source directory exits or not in shell scripts. See example script for more information.

  • 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

A complete list for file testing in bash shell

From the test command man page:

[ Expression ] Meaning
-b filename Return true if filename is a block special file.
-c filename Return true if filename exists and is a character special file.
-d filename Return true filename exists and is a directory.
-e filename Return true filename exists (regardless of type).
-f filename Return true filename exists and is a regular file.
-g filename Return true filename exists and its set group ID flag is set.
-h filename Return true filename exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead.
-k filename Return true filename exists and its sticky bit is set.
-n filename Return true the length of string is nonzero.
-p filename Return true filename is a named pipe (FIFO).
-r filename Return truefilename exists and is readable.
-s filename Return true filename exists and has a size greater than zero.
-t file_descriptor Return true the filename whose file descriptor number is file_descriptor is open and is associated with a terminal.
-u filename Return true filename exists and its set user ID flag is set.
-w filename Return true filename exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true.
-x filename Return true filename exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched.
-z string Return true the length of string is zero.
-L filename Return true filename exists and is a symbolic link.
-O filename Return true filename exists and its owner matches the effective user id of this process.
-G filename Return true filename exists and its group matches the effective group id of this process.
-S filename Return true filename exists and is a socket.
file1 -nt file2 True if file1 exists and is newer than file2.
file1 -ot file2 True if file1 exists and is older than file2.
file1 -ef file2 True if file1 and file2 exist and refer to the same file.

Conclusion

You just learned how to find out if file exists with conditional expressions in a Bash shell. For more information type the following command at shell prompt or see test command in our wiki or see bash man page here:
test(1)

Источник

Читайте также:  Как отключить windows security alerts
Оцените статью