简体   繁体   English

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

[英]Bash script: cd No such file or directory when file exists

My bash script is written to go to each subfolder in the current directory: 我的bash脚本被编写为转到当前目录中的每个子文件夹:

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

When I run my bash script, I am getting a cd error for a directory that exists: 当我运行bash脚本时,出现以下目录的cd错误:

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

Yet, in terminal command line I can do cd 'Zelkova serrata' within the same directory as the script and all is fine. 但是,在终端命令行中,我可以在与脚本相同的目录中执行cd 'Zelkova serrata' ,一切都很好。 Is it possible the bash script has a different source directory than the one its located in? bash脚本的源目录是否可能与其所在的目录不同?

You are looping through relative paths, try including the absolute path, for example: 您正在遍历相对路径,请尝试包括绝对路径,例如:

#!/bin/bash

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

The issue is that the current directory is "state" that is modified on each pass of the loop and to use the posted commands, the cwd state should not be changed by a pass. 问题是当前目录是“状态”,该状态在循环的每次通过中都被修改,并且要使用发布的命令,不应通过传递来更改cwd状态。

Spawning a subshell can fix this problem of mutating state. 生成子外壳可以解决此突变状态的问题。 The subshell inherits the state of its parent, but does not affect the parent. 子shell继承其父级的状态,但不影响父级。

do ( command; command ; ...; ) will spawn a new shell on each loop pass. do ( command; command ; ...; )将在每次循环传递时生成一个新的shell。

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

With bullet proofing 带防弹

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

You'll escape name splitting if there is any space there. 如果那里有空格,您将避免名称拆分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM