Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

shell - 检查外壳脚本中是否存在目录(Check if a directory exists in a shell script)

什么命令可用于检查Shell脚本中是否存在目录?

  ask by Grundlefleck translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To check if a directory exists in a shell script you can use the following:

(要检查shell脚本中是否存在目录,可以使用以下命令:)

if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

Or to check if a directory doesn't exist:

(或检查目录是否不存在:)

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

However, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check.

(但是,正如乔恩·埃里克森Jon Ericson)所指出的,如果您不考虑到目录的符号链接也将通过此检查,则后续命令可能无法按预期运行。)

Eg running this:

(例如运行此:)

ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 
fi

Will produce the error message:

(会产生错误信息:)

rmdir: failed to remove `symlink': Not a directory

So symbolic links may have to be treated differently, if subsequent commands expect directories:

(因此,如果后续命令需要目录,则可能必须区别对待符号链接:)

if [ -d "$LINK_OR_DIR" ]; then 
  if [ -L "$LINK_OR_DIR" ]; then
    # It is a symlink!
    # Symbolic link specific commands go here.
    rm "$LINK_OR_DIR"
  else
    # It's a directory!
    # Directory command goes here.
    rmdir "$LINK_OR_DIR"
  fi
fi

Take particular note of the double-quotes used to wrap the variables, the reason for this is explained by 8jean in another answer .

(请特别注意用于包装变量的双引号,其原因由8jean 在另一个答案中解释。)

If the variables contain spaces or other unusual characters it will probably cause the script to fail.

(如果变量包含空格或其他异常字符,则可能会导致脚本失败。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...