如何在bash中同时循环多个通配符?

时间:2019-02-17 14:47:50

标签: bash shell for-loop wildcard

在bash中,我编写了一个函数,该函数使用通配符循环遍历具有多个扩展名的目录中的文件,并仅复制这些特定文件(如果存在)。代码片段如下所示:

set -e

pushd ../../../../$3/code/project/common/ > /dev/null
mkdir -p ../$2
shopt -s nullglob

for file in *.gyp; do   cp $file ../$2/; done
for file in *.gypi; do  cp $file ../$2/; done
for file in *.sh; do    cp $file ../$2/; done
for file in *.patch; do cp $file ../$2/; done

popd > /dev/null

我宁愿编写一个for file in x语句,这样我就不必为要复制的每个扩展名复制并粘贴此行。

如何将四个for语句重写为一个for语句?如果可能的话,我想将*.ext通配符格式保留在其中。

2 个答案:

答案 0 :(得分:3)

您应该能够做到

for file in *.gyp *.gypi *.sh *.patch; do   cp $file ../$2/; done

答案 1 :(得分:3)

Brace Expansion和一个cp命令:

cp -t ../"$2" *.{gyp,gypi,sh,patch}

除非您确切知道所需的副作用,否则请始终引用变量。