Determine if relative or absolute path in shell pr

2020-02-26 03:52发布

问题:

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?

回答1:

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


回答2:

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

POSIX One Liner

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


回答3:

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


回答4:

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


标签: linux shell path