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

后端 未结 30 2320
猫巷女王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:38

    Remember to always wrap variables in double quotes when referencing them in a Bash script. Kids these days grow up with the idea that they can have spaces and lots of other funny characters in their directory names. (Spaces! Back in my days, we didn't have no fancy spaces! ;))

    One day, one of those kids will run your script with $DIRECTORY set to "My M0viez" and your script will blow up. You don't want that. So use this.

    if [ -d "$DIRECTORY" ]; then
        # Will enter here if $DIRECTORY exists, even if it contains spaces
    fi
    

提交回复
热议问题