0

I have text file, each line containing a string:

input.txt:

This is Line 1
This is Line 2

I want to pass each line as an argument to another script, like so:

consume.sh -n "This is Line 1" -n "This is Line 2"

So what I did was create a script to do this:

file_parser.sh:

IFS=$'\n'
MY_ARGS=
for p in `cat input.txt`
do
  MY_ARGS="${MY_ARGS} -n \"$p\""
done

bash consume.sh $MY_ARGS

It looks like bash is putting quotes around the WHOLE arg, like so:

consume.sh '-n "This is Line 1" -n "This is Line 2"'

How can I construct a string of args to be passed to another script?

grayaii
  • 2,241
  • 7
  • 31
  • 47

1 Answers1

3
  1. Use bash arrays.
  2. Read file using while read, see here .Don't use for i in $(cat file). It's bad.
  3. Properly escape the arguments
  4. Don't use ` ` . Use $( .. ). The ` are deprecated.

args=()
while IFS= read -r line; do 
    args+=(-n "$line")
done < input.txt
consume.sh "${args[@]}"

You can actually even work around bash arrays with some good escaping and eval:

args=""
while IFS= read -r line; do 
     args+=" -n $(printf %q "$line")"; 
done < input.sh
eval consume.sh "$args"
KamilCuk
  • 120,984
  • 8
  • 59
  • 111