如何避免cd到没有访问权限的目录

XYZ*_*nux 1 unix linux bash csh

我有一个数组变量tht包含文件夹中的所有目录.我需要cd到$ array中的每个目录.当它到达不可访问的目录时,程序停止.如何避免这种情况,以便我的循环只是转到下一个目录.代码是

foreach dir ($array) 
  cd $dir
  echo "directory is $dir" 
cd - end
Run Code Online (Sandbox Code Playgroud)

请帮忙 !!

Wil*_*ell 6

只是测试cd工作.

( if cd $dir 2> /dev/null; then
   echo in directory $dir
   # Do other things
fi )
Run Code Online (Sandbox Code Playgroud)

另外,请注意括号.这些导致整个子句在子shell中运行,因此不需要cd回原始位置.