【问题标题】:How to quote the command substitution in a for loop with a variable inside of it?如何在 for 循环中引用命令替换,其中包含一个变量?
【发布时间】:2021-12-13 09:06:17
【问题描述】:

现在,我的 bash 脚本没有按照我的意愿去做。我在我的 bash 脚本上运行“bash -x 脚本”来调试它并测试我当前目录中的所有目录和文件,而不是用户指定的不同目录。告诉我我是如何错误地引用命令替换,这就是问题所在。当我运行它时它不会查看 $dir 变量。

这是我的脚本:

  dir=$1
  
  for i in "$(ls $dir)"
  do
          if [ -d "$i" ]
          then
                     echo "$i"
          fi
  done

【问题讨论】:

  • 语法错误可以使用shellcheck分析你的脚本
  • 这里出现以下错误:for i in "$(ls $dir)" --> (error): Since you double quoted this, it will not word split, and the loop will only run once.
  • 另外,解析 ls is a bad practice。您可能应该使用类似的东西:for i in "$1"/*
  • 脚本打算究竟是做什么的?查找 $1 内的所有目录?
  • 否则你还有一个使用find命令的替代解决方案:find $1 -maxdepth 1 -type d -print

标签: bash script


【解决方案1】:

类似

dir=$1

for f in "$dir"/* ; do
    test -d "$f" || continue
    echo "$f"
done

这里重要的是不要循环$(ls ...),因为它在特殊字符上失败,而是使用$dir"" 保护而不是通配符* 保护的模式。

【讨论】:

    猜你喜欢
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2015-10-12
    • 1970-01-01
    • 2011-07-11
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多