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

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

    More features using find

    • Check existence of the folder within sub-directories:

      found=`find -type d -name "myDirectory"`
      if [ -n "$found"]
      then
          # The variable 'found' contains the full path where "myDirectory" is.
          # It may contain several lines if there are several folders named "myDirectory".
      fi
      
    • Check existence of one or several folders based on a pattern within the current directory:

      found=`find -maxdepth 1 -type d -name "my*"`
      if [ -n "$found"]
      then
          # The variable 'found' contains the full path where folders "my*" have been found.
      fi
      
    • Both combinations. In the following example, it checks the existence of the folder in the current directory:

      found=`find -maxdepth 1 -type d -name "myDirectory"`
      if [ -n "$found"]
      then
          # The variable 'found' is not empty => "myDirectory"` exists.
      fi
      

提交回复
热议问题