How can I check if a given directory is accessible?

后端 未结 1 1789
一向
一向 2020-12-19 20:14

I am currently writing a script that will list all specific files in a directory. What I need the script to do is to verify that the directory is accessible. I am currently

相关标签:
1条回答
  • 2020-12-19 21:06

    Use Bash Conditional Expressions

    On Unix and Linux, practically everything is a file...including directories! If you don't care about execute or write permissions, you can simply check whether a directory is readable with the -r test. For example:

    # Check if a directory is readable.
    mkdir -m 000 /tmp/foo
    [[ -r /tmp/foo ]]; echo $?
    1
    

    You can also check whether a file is a traversable directory in a similar way. For example:

    # Check if variable is a directory with read and execute bits set.
    dir_name=/tmp/bar
    mkdir -m 555 "$dir_name"
    if [[ -d "$dir_name" ]] && [[ -r "$dir_name" ]] && [[ -x "$dir_name" ]]; then
        : # do something with the directory
    fi
    

    You can make the conditionals as simple or as complex as you like, but you don't have to compare octals or parse stat just to check permissions. Bash conditionals can do the job directly.

    0 讨论(0)
提交回复
热议问题