Determine if relative or absolute path in shell program
Asked Answered
P

5

30

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?

Psychodynamics answered 9/7, 2012 at 21:57 Comment(3)
The shell will resolve ~ before it runs the script, so you only need to check for a leading /Dispersion
@Dispersion - only if it is provided as is. In case of echo "~User" it will not. Update: sorry, I've checked the initial question, it was about '${0}', so this is not the case for tilde.Picnic
@loshadvtapkah If you quote the expression then it means literally the relative path in the directory ./~User -- if that's not what you mean, then the quoting is completely a red herring.Vere
C
33
if [[ "$0" = /* ]]
then
   : # Absolute path
else
   : # Relative path
fi
Columnist answered 9/7, 2012 at 22:6 Comment(4)
why do you put [[ ]].Schoolgirl
@DragosRizescu - With [, I would have to escape the asterisk. With (( the asterisk would stop working at all. The point is, you don't want to match the asterisk against files that happen to exist in your root directory; you want to match it against the other argument of the equals operator.Columnist
For zsh single = doesn't work. I had to use the [[ "$0" == /* ]]Tequila
@Tequila - Apparently, the OP and myself are bash users. csh, zsh and some others differ from Bourne shell and bash in using the double equals sign (==) for comparison, because the single equals sign is taken by the assignment operator. This question might need a more specific tag.Columnist
M
21

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

POSIX One Liner

[ "$path" != "${path#/}" ] && echo "absolute" || echo "relative"
Magus answered 15/8, 2016 at 1:40 Comment(0)
S
7
case "$directory" in
   /*)
      echo "absolute"
      ;;
   *)
      echo "relative"
      ;;
esac
Sketch answered 9/7, 2012 at 22:5 Comment(0)
P
0

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"
Plastered answered 22/5 at 18:0 Comment(0)
B
-1
if [ ${path:0:1} == / ]
then
     echo Absolute path
else
     echo Non-absolute path
fi
Bare answered 26/1, 2017 at 13:38 Comment(1)
Please use the edit link to format this code and explain how it works and don't just give the code, as an explanation is more likely to help future readers. See also How to Answer. sourceGobo

© 2022 - 2024 — McMap. All rights reserved.