How can I check if a directory exists in a Bash shell script?

后端 未结 30 2309
猫巷女王i
猫巷女王i 2020-11-22 10:35

What command can be used to check if a directory exists or not, within a Bash shell script?

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 11:17

    if [ -d "$DIRECTORY" ]; then
        # Will enter here if $DIRECTORY exists
    fi
    

    This is not completely true...

    If you want to go to that directory, you also need to have the execute rights on the directory. Maybe you need to have write rights as well.

    Therefore:

    if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
        # ... to go to that directory (even if DIRECTORY is a link)
        cd $DIRECTORY
        pwd
    fi
    

    if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
        # ... to go to that directory and write something there (even if DIRECTORY is a link)
        cd $DIRECTORY
        touch foobar
    fi
    

提交回复
热议问题