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

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

    Note the -d test can produce some surprising results:

    $ ln -s tmp/ t
    $ if [ -d t ]; then rmdir t; fi
    rmdir: directory "t": Path component not a directory
    

    File under: "When is a directory not a directory?" The answer: "When it's a symlink to a directory." A slightly more thorough test:

    if [ -d t ]; then 
       if [ -L t ]; then 
          rm t
       else 
          rmdir t
       fi
    fi
    

    You can find more information in the Bash manual on Bash conditional expressions and the [ builtin command and the [[ compound commmand.

提交回复
热议问题