Jordan
Jordan

Reputation: 2140

Determine if relative or absolute path in shell program

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?

Upvotes: 30

Views: 11084

Answers (5)

If you don't want to expand the directories in /* you can also use regex:

[[   "$foo" =~ ^/ ]] && echo "absolute" || echo "relative"
[[ ! "$foo" =~ ^/ ]] && echo "relative" || echo "absolute"

Upvotes: 0

Jirka Hanika
Jirka Hanika

Reputation: 13529

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

Upvotes: 33

apv
apv

Reputation: 11

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

Upvotes: -1

ryenus
ryenus

Reputation: 17381

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

POSIX One Liner

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

Upvotes: 21

user1277476
user1277476

Reputation: 2909

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

Upvotes: 7

Related Questions