【问题标题】:Check whether subfolder exists in path of filename in bash检查bash中文件名路径中是否存在子文件夹
【发布时间】:2021-11-09 10:54:21
【问题描述】:

我正在尝试检查子文件夹是否在文件路径中,然后仅对该子文件夹中的文件运行操作

for changed_file in $changed_files; do
    echo $changed_file
    if [[ $changed_filed == *'/jsonschema/'* ]];then
        echo  $changed_file  
    else
        echo 'invalid'   
    fi
done

更改的文件包含 ewample:

  • .github/workflows/iglu-lint.yml

  • .schemas/com.myapp/my_context/jsonschema/1-0-1

所以它应该只打印出第二个,但它对两个都打印“无效”。

我的问题是这个检查有什么问题?我无法正确匹配上述路径的语法。

if [[ $changed_filed == *'/jsonschema/'* ]];then

我将其用作 github 操作上的 bash 命令的一部分,试图对上次提交的一些最后文件运行操作。

【问题讨论】:

  • 正则匹配运算符为=~,您这里没有使用正则表达式,请不要使用这个标签。
  • $changed_filed != $changed_file
  • @mgloel :除了变量名中的拼写错误之外,如果其中一个文件路径包含空格,您的方法将失败。我不知道更广泛的背景,但你不能简单地做一个find . -name '*/jsonschema/*' -exec ....吗?
  • 哈哈,打扰了。这是一个愚蠢的错字。非常感谢!
  • 进展如何?问题还不清楚?

标签: bash github-actions glob


【解决方案1】:

对有问题的文件使用数组。

#!/usr/bin/env bash

changed_files=(
  '.github/workflows/iglu-lint.yml'
  '.schemas/com.myapp/my_context/jsonschema/1-0-1'
)

for changed_file in "${changed_files[@]}"; do
  if [[ $changed_file == *'/jsonschema/'* ]];then
    echo  "$changed_file"
  else
    printf >&2 '[%s] is invalid\n' "$changed_file"
  fi
done

上面测试的正则表达式相当于:

[[ $changed_file =~ /jsonschema/ ]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2018-07-17
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    相关资源
    最近更新 更多