如何检查 Bash shell 脚本中是否存在目录?
技术问答
558 人阅读
|
0 人回复
|
2023-09-11
|
在 Bash shell 脚本中可以用什么命令来检查目录是否存在?+ ]! \7 R4 m" k6 M, l' d6 a6 M0 j
' e4 Q" a1 G( R# t 解决方案: 3 J( p; s. X$ C" {( d
要检查 shell 脚本中是否有目录可以使用以下命令:
% B- w* i4 ^9 [% J. d' p* S6 Lif [ -d "$DIRECTORY" ]; then # Control will enter here if $DIRECTORY exists.fi或检查目录是否不存在: E4 ]7 `1 Z u R6 o. W4 F# P
if [ ! -d "$DIRECTORY" ]; then # Control will enter here if $DIRECTORY doesn't exist.fi但是,正如Jon Ericson如果您不考虑目录的符号链接也将通过此检查,则后续命令可能无法按预期工作。例如,操作:/ I3 a, n4 h, J3 B3 n& N
ln -s "$ACTUAL_DIR" "$SYMLINK"if [ -d "$SYMLINK" ]; then rmdir "$SYMLINK" fi产生错误信息:7 P" y" Z4 V& |: u6 U
rmdir: failed to remove `symlink’: Not a directory* b. W: _0 `+ ^5 _# n# p6 w7 t3 \
因此,如果后续命令需要目录,可能需要区分符号链接:if [ -d “$LINK_OR_DIR” ]; then
8 H- ^2 U9 i% f7 N1 Z4 P7 r if [ -L “$LINK_OR_DIR” ]; then( z. b% b/ D. M- \6 @! g
# It is a symlink!: \1 y2 i: J3 g
# Symbolic link specific commands go here.
% A- s; {1 ]; E6 d$ u& A7 c rm “$LINK_OR_DIR”4 O: v8 X) h; ^) `& ^; r6 s& d
else
" e$ g8 K( E/ P! t$ } V' \ # It’s a directory!
( `) U! D7 k" E1 {' K& |; i # Directory command goes here.% V: F6 u! O" u6 ?
rmdir “$LINK_OR_DIR”! G. e2 q {- l3 N% N: }
fi
% Q4 [0 h- K2 F: X& ~+ L* @# ~fi
! u) o1 n6 V! C- f6 {```
* `7 _: b+ f3 [% w" u+ P请特别注意包装变量的双引号。jean在另一个答案中解释了原因。
% s* |2 h5 D7 R' h$ W2 ]3 p如果变量包含空格或其他异常字符,则可能会导致脚本失败。 |
|
|
|
|
|