Bash脚本:cd文件存在时没有这样的文件或目录

时间:2017-07-10 01:13:01

标签: linux bash shell cd

编写我的bash脚本以转到当前目录中的每个子文件夹:

for d in */; 
do
    target=${d%/}
    cd "$target"
done

当我运行bash脚本时,我收到存在的目录的cd错误:

++ for d in '*/'
++ target='Zelkova serrata'
++ cd 'Zelkova serrata'
./script7.sh: line 8: cd: Zelkova serrata: No such file or directory

然而,在终端命令行中,我可以在与脚本相同的目录中执行cd 'Zelkova serrata',一切都很好。 bash脚本是否可能具有与其所在的源目录不同的源目录?

3 个答案:

答案 0 :(得分:3)

您正在循环相对路径,尝试包含绝对路径,例如:

#!/bin/bash

pwd=$PWD
for d in */; 
do
    target="$pwd/${d%/}"
    cd "$target"
    echo $PWD
done

答案 1 :(得分:2)

问题是当前目录是在循环的每次传递中被修改的“状态”并且使用已发布的命令,cwd状态不应该通过传递来改变。

产生一个子shell可以解决这个状态变异的问题。子shell继承其父级的状态,但不影响父级。

do ( command; command ; ...; )将在每个循环传递上生成一个新shell。

for d in */; 
do (
  target=${d%/}
  cd "$target"
) done

答案 2 :(得分:0)

使用防弹

~$ find /full/path/to/dir -maxdepth 1 -type d -printo | xargs -0 -I% sh -c "cd %; echo "do some fun here""

如果那里有任何空间,你将逃脱名称分裂。