我正在尝试编写一个简单的程序来检查给定的文件名是否指向目录。但是当我运行 ./isdir.sh(这是脚本的名称)时,我一直收到错误提示“错误的解释器:没有这样的文件或目录”。
这是我的代码:
#!bin/sh
if [[ $# -ne 1 ]];then
echo "Usage: $0 dir"
exit 1
fi
dir="$1"
dirname = "$1"
if [[ ! -d "$dir" ]]; then
echo "Error: directory $dir not found."
exit 2
fi
if [[ -d "$dirname" ]]; then
echo "$dirname is a directory."
exit 3
还有一个重要的问题: 如何处理其中包含空格的输入值?
最佳答案
你可以这样做:
#!/bin/bash
if [[ $# -ne 1 ]]; then
echo "Usage: $0 dir"
exit 2
fi
dir="$1"
rc=1
if [[ -d "$dir" ]]; then
# it is a directory
rc=0
elif [[ -e "$dir" ]]; then
echo "Error: '$dir' is not a directory"
else
echo "Error: directory '$dir' does not exist"
fi
exit "$rc"
- 不需要
dirname
变量。 - 该脚本对于名称中包含空格或通配符的目录是安全的,因为我们已将变量括在双引号中。
- 退出代码 2 是无效参数错误的 Unix 标准; exit 1 是所有其他错误。但是,您可以根据需要更改退出代码。
有关此问题的更多观点,请参阅此相关帖子:Check if a directory exists in a shell script
关于linux - 如何检查用户指定的名称是否引用目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42059594/