确定外壳程序,如果相对或绝对路径(Determine if relative or absolute

2019-06-26 04:17发布

正如标题所说,我需要确定什么时候如果路径是相对或绝对的程序运行:

./program #relative
dir/dir2/program #relative
~User/dir/dir2/program #absolute
/home/User/dir/dir2/program #absolute

这是我的测试用例。 我可以去正是如何在shell程序这样做呢?

或者更一般地说,如何检查的路径, $0在这种情况下,是相对或绝对的?

Answer 1:

if [[ "$0" = /* ]]
then
   : # Absolute path
else
   : # Relative path
fi


Answer 2:

对于任何的一般解$path ,而不是仅仅$0

POSIX一个班轮

[ "$path" != "${path#/}" ] && echo "absolute" || echo "relative"


Answer 3:

case "$directory" in
   /*)
      echo "absolute"
      ;;
   *)
      echo "relative"
      ;;
esac


Answer 4:

if [ ${path:0:1} == / ]
then
     echo Absolute path
else
     echo Non-absolute path
fi


文章来源: Determine if relative or absolute path in shell program
标签: linux shell path