0

thank you for taking time to help!

I'm trying to run a command 1 time with a variable as the argument. The thing is, the variable has multiple lines, and I need to run a command 1 time for each line as the argument.

Example script

VAR1=command1

"${VAR1}" | xargs -L1 -d "\n command2$i

The example output for VAR1 is

1111
2222
3333
4444
5555

I need to run command2 one time per line, so

command2 1111
command2 2222
command2 3333
command2 4444
command2 5555

I have tried this as well,

VAR1=command1

"${VAR1}" | while read line ; do command2$i

and this

VAR1=command1

"${VAR1}" | while read line ; do command2"${VAR1}"

Thank you for yalls time!

1 Answers1

1

For xargs, you can use a "here string":

xargs -L1 command2 <<< "$var1"

or simply

printf '%s\n' "$var1"  | xargs -L1 command2

And similarly for the loop, but you need to really use the loop variable:

while read -r line ; do
    command2 "$line"
done <<< "$var1"

or, again,

printf '%s\n' "$var1" | while read -r line ; do
    command2 "$line"
done
choroba
  • 231,213
  • 25
  • 204
  • 289
  • You might need to use `printf '%s\n'` if the variable doesn't include a terminating newline. (On the other hand, `<<< "$var1"` *does* append a newline, so if the variable has a terminating newline you'll get a blank line at the end.) – Gordon Davisson Oct 13 '20 at 01:10
  • @gordondavisson I tested the solution and it seems to work without the newline. – choroba Oct 13 '20 at 05:38
  • `xargs` will tolerate a missing final linefeed (at least the versions I tested do), but [`while read` won't](https://stackoverflow.com/questions/12916352/shell-script-read-missing-last-line/). – Gordon Davisson Oct 13 '20 at 06:44
  • @GordonDavisson: You're right, I had an error in my tests. – choroba Oct 13 '20 at 07:59