Determine if relative or absolute path in shell program

前端 未结 4 1031
再見小時候
再見小時候 2020-12-29 04:33

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/d         


        
相关标签:
4条回答
  • 2020-12-29 04:58
    case "$directory" in
       /*)
          echo "absolute"
          ;;
       *)
          echo "relative"
          ;;
    esac
    
    0 讨论(0)
  • 2020-12-29 05:00
    if [ ${path:0:1} == / ]
    then
         echo Absolute path
    else
         echo Non-absolute path
    fi
    
    0 讨论(0)
  • 2020-12-29 05:07

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

    POSIX One Liner

    [ "$path" != "${path#/}" ] && echo "absolute" || echo "relative"
    
    0 讨论(0)
  • 2020-12-29 05:08
    if [[ "$0" = /* ]]
    then
       : # Absolute path
    else
       : # Relative path
    fi
    
    0 讨论(0)
提交回复
热议问题