运行 仅当至少有一个 json 文件时才进行循环
Run for-loop only if there is at least one json file
我想遍历特定子目录中的所有 json 个文件。
#!/bin/sh
source_dir="nodes"
for file_path in $source_dir/*.json;
do
file_name=$(basename $file_path .${file_path##*.})
echo $file_name
done
如果目录中至少有一个 json 文件,我的代码将按预期工作。
如果目录下没有json文件,还是会执行循环。 file_name 然后是 "*"。
如何更改 for 循环,使其仅在目录中至少有一个 json 文件时才执行?
您可以将循环包裹在 if 子句中以检查模式是否匹配任何内容。
检查此 SO 问题以了解如何执行此操作:Check if a file exists with wildcard in shell script
我想遍历特定子目录中的所有 json 个文件。
#!/bin/sh
source_dir="nodes"
for file_path in $source_dir/*.json;
do
file_name=$(basename $file_path .${file_path##*.})
echo $file_name
done
如果目录中至少有一个 json 文件,我的代码将按预期工作。 如果目录下没有json文件,还是会执行循环。 file_name 然后是 "*"。
如何更改 for 循环,使其仅在目录中至少有一个 json 文件时才执行?
您可以将循环包裹在 if 子句中以检查模式是否匹配任何内容。
检查此 SO 问题以了解如何执行此操作:Check if a file exists with wildcard in shell script