Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop over multiple wildcards simultaneously in bash?

In bash, I've written a function that loops over files in a directory with multiple extensions using wildcards, and copies only these specific files if they exist. A snippet of the code looks like this:

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

I'd prefer instead to write one for file in x statement, so that I don't have to copy and paste this line for each extension I want to copy.

How can I rewrite the four for statements as one for statement? I would like to keep the *.ext wildcard format somewhere in there if possible.

like image 593
tjgrant Avatar asked Jan 26 '23 17:01

tjgrant


2 Answers

You should just be able to do

for file in *.gyp *.gypi *.sh *.patch; do   cp $file ../$2/; done
like image 186
Joe Avatar answered Jan 29 '23 21:01

Joe


Brace Expansion and a single cp command:

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

Always quote your variables, unless you know exactly what side-effects you want.

like image 22
glenn jackman Avatar answered Jan 29 '23 19:01

glenn jackman