Reputation: 2140
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
Reputation: 31
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
Reputation: 13529
if [[ "$0" = /* ]]
then
: # Absolute path
else
: # Relative path
fi
Upvotes: 33
Reputation: 11
if [ ${path:0:1} == / ]
then
echo Absolute path
else
echo Non-absolute path
fi
Upvotes: -1
Reputation: 17381
A general solution for any $path
, rather than just $0
[ "$path" != "${path#/}" ] && echo "absolute" || echo "relative"
Upvotes: 21
Reputation: 2909
case "$directory" in
/*)
echo "absolute"
;;
*)
echo "relative"
;;
esac
Upvotes: 7