我试图找出如何设置将执行以下操作的脚本:
dir中的文件:
a_3.txt
b_3.txt
c_3.txt
目录中的脚本:
1.sh # run this for a_*.txt
2.sh # run this for b_*.txt or c_*.txt
我需要一个能够选择文件并通过指定脚本运行它的函数。
fname = "c_*.txt" then
if "${fname}" = "c_*.txt"
./1.sh ${fname} [param1] [param2]
fi
或某些种类。该脚本将与它将使用的文件/脚本位于同一位置。用语言来说,脚本将根据文件名的开头和filetype / suffix运行指定的脚本。任何帮助将不胜感激。
答案 0 :(得分:3)
选择所有内容和过滤比逐个模式更麻烦。
#!/bin/bash
# ^^^^- bash is needed for nullglob support
shopt -s nullglob # avoid errors when no files match a pattern
for fname in a_*.txt; do
./1.sh "$fname" param1 param2 ...
done
for fname in b_*.txt c_*.txt; do
./2.sh "$fname" param2 param3 ...
done
也就是说,如果确实想要遍历目录中的所有文件,请使用case
语句:
# this is POSIX-compliant, and will work with #!/bin/sh, not only #!/bin/bash
for fname in *; do # also consider: for fname in [abc]_*.txt; do
case $fname in
a_*.txt) ./1.sh "$fname" param1 param2 ... ;;
b_*.txt|c_*.txt) ./2.sh "$fname" param1 param2 ... ;;
*) : "Skipping $fname" ;; # this will be logged if run with bash -x
esac
done