Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: xargs passing variable

How can a global script variable be passed to the command of xargs? I tried it this way:

TEST=hallo2
echo "hallo" | xargs sh -c 'echo passed=$1 test=$TEST' sh

Output:

passed=hallo test=

I know I could use the {} token but I need to do it this way!

I'm using bash.

like image 660
arminb Avatar asked Mar 15 '13 11:03

arminb


People also ask

What xargs 0?

xargs options : -0 : input items are terminated by null character instead of white spaces. -a file : read items from file instead of standard input.

What is xargs I option?

xargs gets the needed arguments from standard input (the standard input). Different options tell how the standard input is to be interpreted to obtain these arguments. -I placeholder Specifies that each line in the standard input (the standard input) is to be considered as a single argument.

What is xargs grep?

xargs command in UNIX or Linux is a powerful command used in conjunction with find and grep command in UNIX to divide a big list of arguments into small list received from standard input.


2 Answers

Added as an answer as@chepner suggested.

export the variable TEST:

export TEST=hallo2
echo "hallo" | xargs sh -c 'echo passed=$1 test="$TEST"' sh
like image 92
Carlos Campderrós Avatar answered Sep 22 '22 18:09

Carlos Campderrós


Take variable $TEST out from the quotes:

 TEST=hallo2
 echo "hallo" | xargs sh -c 'echo passed=$1 test='$TEST sh
like image 21
Ander2 Avatar answered Sep 20 '22 18:09

Ander2