Test if a script can cd into a directory

Is there a way for a bash script to test if it can cd into a directory without actually attempting to cd into it?

I am looking for something along the lines of:

if [ -d $dir ];then
     #code to execute
fi

except in this case I don't want to test if the directory exists; what I want is to test if the script has the permission to cd into the directory.
I know there are other ways of achieving this but does bash provide a shortcut? :wink:

A process can "cd" into a directory when it has execute-rights on it. Test simply if it is a directory AND if the x-bit is set for you:

if [ -d "$dir" -a -x "$dir" ] ; then
     # do something here
fi

I hope this helps.

bakunin

1 Like

You can also try:

if ( cd "$dir" 2>/dev/null )
then    # do something
fi

If you want the diagnostic from cd if the cd failed, drop the redirection, or if you want a custom diagnostic add an else clause to your if statement. Performing the cd in a subshell will not affect the current working directory for the rest of this script.

Some people find this form easier to understand, but creating a subshell won't be as efficient as running

test -d "$dir" && test -x "$dir"

in the current shell execution environment.

1 Like

Just test $?. If it's zero, the "cd" worked.

I vote for

test -d "$dir"/.

This fosters an autofs mount or an AFS volume mount, so is as safe as an actual cd . No need for an additional test -x .

3 Likes

That's insufficient. If all but the final path component have execute/search permission, the stat() syscall for test -d succeeds, but the chdir() syscall for cd fails.

Regards,
Alister

ok. insightful -- doing the cd in a subshell. thanks!

---------- Post updated at 02:14 AM ---------- Previous update was at 02:13 AM ----------

exactly what i was hoping to find. thanks.

Which is why MadeInGermany added the /. in the suggestion:

test -d "$dir"/.

If the caller doesn't have search permission in $dir , pathname resolution for "$dir"/. will fail, so test -d "$dir"/. , chdir($dir), chdir($dir/.), and stat($dir/.) will all fail.

Yeah. I overlooked the /. when I responded to the post.

Also, I don't think your response to my post was up when I went to edit/delete. Since there's a response to it, perhaps you should undelete it (if possible).

Regards,
Alister