linux - Check if a directory exists and is accessible -
i want check if directory exists , has access rights; if does, perform tasks. code wrote, might not have proper syntax.
can me correct it?
dir_test=/data/abc/xyz if (test -d $dir_test & test –x $dir_test -eq 0); cd $dir_test fi
i believe can written this.
dir_test=/data/abc/xyz test -d $dir_test if [ $? -eq 0 ]; test –x $dir_test if [ $? -eq 0 ]; cd $dir_test fi fi
how can write more efficiently?
the best way write original test
-based solution be
if test -d "$dir_test" && test –x "$dir_test"; cd $dir_test fi
although if test fails , don't change directories? remainder of script not work expected.
you can shorten using [
synonym test
:
if [ -d "$dir_test" ] && [ -x "$dir_test" ];
or can use conditional command provided bash
:
if [[ -d "$dir_test" && -x "$dir_test" ]];
the best solution, since going change directories if tests succeed, try it, , abort if fails:
cd "$dir_test" || { # take appropriate action; 1 option exit # error. exit 1 }
Comments
Post a Comment