5

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?

muru
  • 197,895
  • 55
  • 485
  • 740
ErikM
  • 153
  • 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 '17 at 15:48

2 Answers2

7

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
Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497
5

Using a while loop:

#!/bin/bash
while IFS= read -r line; do
   # if the line read is empty 
   # go to the next line. Skips empty lines
   if [ -z "${line}" ]
   then
       continue
   fi
  /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

George Udosen
  • 36,677
  • 1
    you could directly send the file with the params to the loop: done < params_file – pLumo Jun 12 '17 at 12:13
  • Yes I know but I prefer this so OP can change the fed in file as desired – George Udosen Jun 12 '17 at 12:15
  • True. I just would not put such a simple while loop into an own script ;-) But that is a matter of taste of course. – pLumo Jun 12 '17 at 12:17
  • 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 – Sergiy Kolodyazhnyy Jun 12 '17 at 12:29
  • 2
    [[ -n "$line" ]] && ./MyScript.sh $line would be way shorter, 1 instead of 5 lines – pLumo Jun 12 '17 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 '17 at 14:48