【问题标题】:check for existance of directory doesn't fail in bash检查目录是否存在在 bash 中不会失败
【发布时间】:2018-03-06 20:19:39
【问题描述】:

当我给脚本一个参数时,下面的 shell 脚本可以正常工作。 [ ./test 目录名 ]

但是,当我不提供目录名称时,脚本不会失败 [即不会陷入错误消息]。在这种情况下脚本不会失败的任何原因?

#!/bin/sh
echo "directory name is " $1
if [ ! -d $1 ];  
then
  echo "ERROR: directory doesn't exist"
fi

【问题讨论】:

  • 引用它:[ ! -d "$1" ]
  • 或者使用 Bash 构造 [[...]] - if [[ -d $1 ]]; ...

标签: linux bash shell sh


【解决方案1】:

由于您没有引用$1,并且它的扩展是空字符串,因此扩展经过分词后您的命令变为[ ! -d ]。您正在测试字符串 -d 是否为非空,它是。

总是 引用参数扩展;你会知道什么时候做的不对。

echo "directory name is $1"

if [ ! -d "$1" ]; then

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-07
    • 2020-08-09
    • 2023-03-04
    • 2012-04-05
    • 2015-01-29
    • 2017-06-11
    • 2011-10-28
    • 1970-01-01
    相关资源
    最近更新 更多