How to see if the directory exists?

14,336

You can use the following to check for the existence of a directory:

if [[ -d "$1" ]]; then

If you want to check for any file you would use

if [[ -e "$1" || -L "$1" ]]; then

If you want to check if a file is a regular file (or symlink to regular file), but NOT a directory (or a device, socket, named pipe...) file then you can use:

if [[ -f "$1" ]]; then

If the file might exist but you want to be sure it is not zero size:

if [[ -s "$1" ]] then;

All those tests are based on the result of the stat() system call (except for -L that relies on lstat()). If you don't have the permission to do such a call on the file (for example because you don't have search access to the directory the file is in or to directories involved in the resolution of the file for symlinks), then those tests will silently return false as if the files didn't exist.

[[ ... ]] is a ksh operator, also supported by bash and zsh. The standard equivalent (to use in sh) is with the [ command (for the second example above, use [ -e "$1" ] || [ -L "$1" ]).

Share:
14,336

Related videos on Youtube

user3334375
Author by

user3334375

Updated on September 18, 2022

Comments

  • user3334375
    user3334375 over 1 year

    How can I check if /bin/x86_64/bin/ls is a directory in a bash shell script

    Here is what I tried:

    #!/bin/bash
    
    if [ $# -eq 2 ]; then
        if [[ "$1" = /* ]]
        then
        cd ./bin/x86_64/bin/ls
            if [ -d "$1" ]; then
                echo "ok"
                i="$1"
                echo $i
            else
                echo "error2"
                exit
            fi
        else
            echo "error"
            exit
        fi
    fi
    
    • Skaperen
      Skaperen almost 9 years
      did you mean if [[ "$1" = "/*" ]]?
    • Michael Durrant
      Michael Durrant almost 9 years
      the cd ./bin/x86_65/bin/ls seems unusual. Try a format more like cd "/bin/x86_64/bin" using quotes and omitting the ls at the end as that is probably a command not a directory.
    • Michael Durrant
      Michael Durrant almost 9 years
      Also, do you get an error ?
  • user3334375
    user3334375 almost 9 years
    doesn;t work :(
  • Michael Durrant
    Michael Durrant almost 9 years
    In what way and AGAIN what error(s) do you get? It's good that you provide the details of what you have attempted, however you are unlikely to get much help unless you respond to the requests for more details about what error or response you get.
  • ryanpcmcquen
    ryanpcmcquen over 8 years
    If you use single brackets these commands will have more compatibility.