Determine if relative or absolute path in shell pr

2020-02-26 04:11发布

As stated in the title, I need to determine when a program is ran if the path is relative or absolute:

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

This are my test cases. How exactly could I go about doing this in a shell program?

Or more generally, how to check if a path, $0 in this case, is relative or absolute?

标签: linux shell path
4条回答
forever°为你锁心
2楼-- · 2020-02-26 04:32

A general solution for any $path, rather than just $0

POSIX One Liner

[ "$path" != "${path#/}" ] && echo "absolute" || echo "relative"
查看更多
Lonely孤独者°
3楼-- · 2020-02-26 04:46
if [ ${path:0:1} == / ]
then
     echo Absolute path
else
     echo Non-absolute path
fi
查看更多
唯我独甜
4楼-- · 2020-02-26 04:49
if [[ "$0" = /* ]]
then
   : # Absolute path
else
   : # Relative path
fi
查看更多
倾城 Initia
5楼-- · 2020-02-26 04:50
case "$directory" in
   /*)
      echo "absolute"
      ;;
   *)
      echo "relative"
      ;;
esac
查看更多
登录 后发表回答