linux - 如何检查用户指定的名称是否引用目录?

标签 linux bash shell

我正在尝试编写一个简单的程序来检查给定的文件名是否指向目录。但是当我运行 ./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/

相关文章:

linux - 我可以在 awk 的不同代码块中使用不同的分隔符吗?

html - 查找所有扩展名为 .md 的文件并使用该文件执行命令并生成一个新文件,其名称通过 md 文件名生成

linux - 使用 nohup 调用函数

linux - 如何在 bash 中记录输出并同时在终端中看到它?

带有 IF ELSE 语句的 BASH Shell 无限循环

bash - 以给定的行数从 file1 到 file2 交错文本文件

c++ - linux下nanopi2 fire的硬件编码

python - 如何在 bash 脚本中使用 Python 3.6 解释器?

linux - tar 文件,包括没有 sibling 的目录

bash - Ubuntu 脚本在 CRON 中不起作用