shell - Get current directory and concatenate a path -


this shell script (.sh file). need create absolute path based on current directory. know pwd, how concatenate string? here example of trying do:

"$pwd/some/path" 

sounds want:

path="$(pwd)/some/path" 

the $( opens subshell (and ) closes it) contents executed script outputs put in location in string.


more useful getting directory of script running:

dot="$(cd "$(dirname "$0")"; pwd)" path="$dot/some/path" 

that's more useful because resolves same path no matter when run script:

> pwd ~ > ./my_project/my_script.sh ~/my_project/some/path 

rather than:

> pwd ~ > ./my_project/my_script.sh ~/some/path > cd my_project > pwd ~/my_project > ./my_script.sh ~/my_project/some/path 

more complex if need directory of current script running if has been executed through symlink (common when installing scripts through homebrew example) need parse , follow symlink:

if [[ "$ostype" == *darwin* ]];   readlink_cmd='greadlink' else   readlink_cmd='readlink' fi  dot="$(cd "$(dirname "$([ -l "$0" ] && $readlink_cmd -f "$0" || echo "$0")")"; pwd)" 

more complex , more requirements work (e.g. having gnu compatible readlink installed) tend not use much. when i'm need it, installing command through homebrew.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

android - MPAndroidChart - How to add Annotations or images to the chart -