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

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

    1. A simple script to test if a directory or file is present or not:

       if [ -d /home/ram/dir ]   # For file "if [ -f /home/rama/file ]"
       then
           echo "dir present"
       else
           echo "dir not present"
       fi
      
    2. A simple script to check whether the directory is present or not:

       mkdir tempdir   # If you want to check file use touch instead of mkdir
       ret=$?
       if [ "$ret" == "0" ]
       then
           echo "dir present"
       else
           echo "dir not present"
       fi
      

      The above scripts will check if the directory is present or not

      $? if the last command is a success it returns "0", else a non-zero value. Suppose tempdir is already present. Then mkdir tempdir will give an error like below:

      mkdir: cannot create directory ‘tempdir’: File exists

提交回复
热议问题