shell - Bash: check if a relative path exists -
i writing shell script takes in directory argument. need check if directory exists before else. directory can absolute or relative. know can check existence of absolute directory (say, /users/keith/documents/testfolder) using
if [ -d "$1"]; # if absolute directory exists fi
however, if working directory /users/keith/documents/ , call script , pass "testfolder", test in if statement evaluate false, though testfolder exists within current working directory.
i have tried converting directory absolute directory using
abs_path=`cd "$1"; pwd`
and testing existence of absolute path using if statement above. works fine (recognizes "testfolder" exists if that's pass argument) provided directory passed script indeed exist, if doesn't fails.
what need way determine whether directory passed argument exists, regardless of whether passed absolute directory or 1 relative user's current working directory, , cannot fail if directory doesn't exist.
i no bash expert - advice appreciated!
however, if working directory /users/keith/documents/ , call script , pass "testfolder", test in if statement evaluate false, though testfolder exists within current working directory.
that's not correct. if testfolder
exists in current working directory, [ -d testfolder ]
succeed. there no problem here.
by way, if want canonicalize filepath , have gnu coreutils (which if have linux system), can use:
readlink -f "$path"
or
readlink -e "$path"
the difference -f
succeed if last component in path doesn't exist (so succeed if path plausible name file created), while -e
succeed if path resolves existing file or directory. see man readlink
more details.
Comments
Post a Comment