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

时间:2013-11-25 22:35:29

标签: bash shell

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

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

#!/bin/bash

DIR=$1

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

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

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

由于某些原因,我似乎无法弄清楚这个错误。有什么想法吗?

5 个答案:

答案 0 :(得分:33)

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

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

答案 1 :(得分:24)

只测试第一个字符:

if [ "${DIR:0:1}" = "/" ]

答案 2 :(得分:5)

编写测试很有趣:

#!/bin/bash

declare -a MY_ARRAY # declare an indexed array variable

MY_ARRAY[0]="/a/b"
MY_ARRAY[1]="a/b"
MY_ARRAY[2]="/a a/b"
MY_ARRAY[3]="a a/b"
MY_ARRAY[4]="/*"


# Note that 
# 1) quotes around MY_PATH in the [[ ]] test are not needed
# 2) the expanded array expression "${MY_ARRAY[@]}" does need the quotes
#    otherwise paths containing spaces will fall apart into separate elements.
# Nasty, nasty syntax.

echo "Test with == /* (correct, regular expression match according to the Pattern Matching section of the bash man page)"

for MY_PATH in "${MY_ARRAY[@]}"; do
   # This works
   if [[ $MY_PATH == /* ]]; then
      echo "'$MY_PATH' is absolute"
   else
      echo "'$MY_PATH' is relative"
   fi
done

echo "Test with == \"/*\" (wrong, becomes string comparison)"

for MY_PATH in "${MY_ARRAY[@]}"; do
   # This does not work at all; comparison with the string "/*" occurs!
   if [[ $MY_PATH == "/*" ]]; then
      echo "'$MY_PATH' is absolute"
   else
      echo "'$MY_PATH' is relative"
   fi
done

echo "Test with = /* (also correct, same as ==)"

for MY_PATH in "${MY_ARRAY[@]}"; do
   if [[ $MY_PATH = /* ]]; then
      echo "'$MY_PATH' is absolute"
   else
      echo "'$MY_PATH' is relative"
   fi
done

echo "Test with =~ /.* (pattern matching according to the regex(7) page)"

# Again, do not quote the regex; '^/' would do too

for MY_PATH in "${MY_ARRAY[@]}"; do
   if [[ $MY_PATH =~ ^/[:print:]* ]]; then
      echo "'$MY_PATH' is absolute"
   else
      echo "'$MY_PATH' is relative"
   fi
done

答案 3 :(得分:4)

ShellCheck会自动指出“[ .. ] can't match globs. Use [[ .. ]] or grep.

换句话说,使用

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

这是因为[是一个常规命令,所以/*预先由shell扩展,将其转换为

[ "$DIR" = /bin /dev /etc /home .. ]

[[由shell专门处理,没有这个问题。

答案 4 :(得分:4)

另一个案例是从~(代字号)开始的路径。 ~user/some.file~/some.file是某种绝对路径。

if [[ "${dir:0:1}" == / || "${dir:0:2}" == ~[/a-z] ]]
then
    echo "Absolute"
else
    echo "Relative"
fi
相关问题