bashshell

How to check if a shell script $1 parameter is an absolute or relative path?


As the title says, I am trying to determine if my BASH script receives as a parameter: a full path, or a relative file to a directory.

For some reasons the following doesn't seem to work for me:

#!/bin/bash

DIR=$1

if [ "$DIR" = /* ]
then
    echo "absolute"
else
    echo "relative"
fi

When I run my script with either a full path or absolute path it says:

./script.sh: line 5: [: too many arguments
relative

For some reasons I can't seem to figure this bug. Any ideas?


Solution

  • [ ... ] doesn't do pattern matching. /* is being expanded to the contents of /, so effectively you have

    if [ "$DIR" = /bin /boot /dev /etc /home /lib /media ... /usr /var ]
    

    or something similar. Use [[ ... ]] instead.

    if [[ "$DIR" = /* ]]; then
    

    For POSIX compliance, or if you just don't have a [[ that does pattern matching, use a case statement.

    case $DIR in
      /*) echo "absolute path" ;;
      *) echo "something else" ;;
    esac