【问题标题】:Bash script: cd No such file or directory when file existsBash脚本: cd 文件存在时没有这样的文件或目录
【发布时间】:2017-07-10 01:13:01
【问题描述】:

我的 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 脚本的源目录是否可能与其所在的目录不同?

【问题讨论】:

  • 在使用 Linux 时,我倾向于尽可能避免使用带有空格的文件和目录名称。 CamelCase 或 under_score 几乎一样易于阅读、更常见且更安全。
  • @Paul:绝对同意!不幸的是,我在继承代码时没有设计它的结构
  • cd $target 之前添加pwd,看看这是否揭示了任何有趣的东西......

标签: linux bash shell cd


【解决方案1】:

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

#!/bin/bash

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

【讨论】:

    【解决方案2】:

    问题是当前目录是“状态”,在每次循环时都会修改,并且要使用发布的命令,cwd 状态不应该通过一次来更改。

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

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

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

    【讨论】:

      【解决方案3】:

      防弹

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

      如果那里有空格,您将避免名称拆分。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-16
        • 2020-05-09
        • 2017-08-06
        • 1970-01-01
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 2016-05-06
        相关资源
        最近更新 更多