bash - 检查 Shell 脚本 $1 是绝对路径还是相对路径

标签 bash shell

<分区>

正如标题所说,我正在尝试确定我的 bash 脚本是否接收到目录的完整路径或相对文件作为参数。

由于某些原因,以下内容似乎对我不起作用:

#!/bin/bash

DIR=$1

if [ "$DIR" = /* ]
then
    echo "absolute"
else
    echo "relative"
fi

当我使用完整路径或绝对路径运行我的脚本时,它会显示:

./script.sh: line 5: [: too many arguments
relative

出于某些原因,我似乎无法理解这个错误。有什么想法吗?

最佳答案

[ ... ] 不进行模式匹配。 /* 被扩展为 / 的内容,因此您有效地拥有了

if [ "$DIR" = /bin /boot /dev /etc /home /lib /media ... /usr /var ]

或类似的东西。请改用 [[ ... ]]

if [[ "$DIR" = /* ]]; then

为了符合 POSIX,或者如果您只是没有执行模式匹配的 [[,请使用 case 语句。

case $DIR in
  /*) echo "absolute path" ;;
  *) echo "something else" ;;
esac

关于bash - 检查 Shell 脚本 $1 是绝对路径还是相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204820/

相关文章:

json - 使用 shell 脚本在特定数组索引后附加 JSON 文件

shell - 如何从我的 Cocoa 应用程序运行 shell 命令?

shell - awk 语法错误 : syntax error at source line 1

linux - 使用 ssh 运行带参数的远程 bash 脚本

linux - 如何在终端上将二进制文本转换为 ASCII?

linux - Shell 脚本未通过 Linux Mint 上的 crontab 运行

bash - 使用进程替换与管道有什么区别?

arrays - 如何在 bash 中拒绝空数组索引

bash - 如何将 'gvim filename' 别名为 'gvim filename &'

Shell 命令对整数求和,每行一个?