I have a command that takes a file name as a variable, I have given it as a name pattern, file_*_123.txt

Script.sh file_*_123.txt

Now if there are more than one files with matching pattern it only executes for the first file, I want this script to be executed for each file matching the name pattern. for e.g. file_1_123.txt, file_2_123.txt, file_3_123.txt

Someone kind of for loop. However, because the number of file(s) can be 1 or more than 1 so not sure how to iterate through.

Can anyone please suggest a solution to it.

  • Check the man page for find, specifically the -exec option.
    – ivanivan
    Jul 17, 2018 at 14:25

2 Answers 2


This would either involve calling your script in a loop, or arranging for your script to loop over its command line arguments.

The first option:

for filename in file_*_123.txt; do
    ./Script.sh "$filename"

This would call your script once for each file that matches the pattern file_*_123.txt.

The second option:

You would modify the script and wrap the body of it in a loop, such as


for filename do
    # here you do whatever you need to do with "$filename"



for filename in "$@"; do
    # here you do whatever you need to do with "$filename"

(these two variants of the loop are equivalent)

This would cause the script to loop over its command line arguments. You would then run your script as you have shown in the question:

./Script.sh file_*_123.txt

If you wanna execute these matched files in parallel, you may consider use utility parallel

code sample

    /PATH/Script.sh "${file_path}"

# make function funcXXXX can be used by parallel
export -f funcXXXX

ls /PATH/file_*_123.txt | xargs -l | parallel -k -j 0 funcXXXX

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .