I got a file with some params of a script:

foo1 a b c
foo2 a b c
foo3 a b c

I need to run a script once for each line in this file passing the line as script arg, so it should do:

./MyScript.sh foo1 a b c
./MyScript.sh foo2 a b c
./MyScript.sh foo3 a b c

How can I achieve this using Bash?

  • If what you need is to further process each line of the file and execute things accordingly, maybe awk is what you are looking for.
    – Samuel
    Jun 12, 2017 at 15:48

2 Answers 2


xargs command, which is created for running a command with arguments that are read from stdin has a --arg-file parameter, which allows reading arguments from file. In combination with-L1 flag, it will read your arguments file line by line, and for each line execute the command. Here's an example:

$ cat args.txt
one two three
four file six

$ xargs -L1 --arg-file=args.txt echo                       
one two three
four file six

Replace echo with your script.

Alternatively, you can always redirect the file to be read by xargs from stdin stream like so:

$ xargs -L1  echo < args.txt                                                                                             
one two three
four file six

Using a while loop:

while IFS= read -r line; do
   # if the line read is empty 
   # go to the next line. Skips empty lines
   if [ -z "${line}" ]
  /path/to/MyScript.sh $line
done < "$1"

Then call this script anything.sh and run it like this:

anything.sh /path/to/file/with/foo

Remember to make both anything.sh and MyScript.sh executable

  • 1
    you could directly send the file with the params to the loop: done < params_file
    – pLumo
    Jun 12, 2017 at 12:13
  • Yes I know but I prefer this so OP can change the fed in file as desired Jun 12, 2017 at 12:15
  • 2
    Your for loop won't read file line by line. Change it to (IFS=$'\n'; for line in $(cat args.txt); do script.sh "$line"; done). In general it's not the best approach. The while loop is preferable Jun 12, 2017 at 12:29
  • 2
    [[ -n "$line" ]] && ./MyScript.sh $line would be way shorter, 1 instead of 5 lines
    – pLumo
    Jun 12, 2017 at 12:36
  • 1
    @RoVo Also much more obscure. Sometimes, a few extra lines are a perfectly good trade-off when the result is much more readable, particularly for a beginner.
    – user
    Jun 12, 2017 at 14:48

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