15

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.

arminb
  • 2,036
  • 3
  • 24
  • 43

3 Answers3

12

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
Carlos Campderrós
  • 22,354
  • 11
  • 51
  • 57
11

Take variable $TEST out from the quotes:

 TEST=hallo2
 echo "hallo" | xargs sh -c 'echo passed=$1 test='$TEST sh
Ander2
  • 5,569
  • 2
  • 23
  • 42
  • 6
    If you take this approach, you should double-quote `$TEST` to guard against it containing whitespace. – chepner Mar 15 '13 at 13:15
-6

With GNU Parallel you can avoid some of the quoting:

TEST=hallo2
echo "hallo" | parallel echo passed={} test=$TEST

GNU Parallel exists as package for most distributions and it is recommended to use the normal package manager for installation. But if there is no package for your system, it still takes literally 10 seconds to install GNU Parallel.

Watch the intro videos to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

justin.m.chase
  • 13,061
  • 8
  • 52
  • 100
Ole Tange
  • 31,768
  • 5
  • 86
  • 104
  • 16
    I strongly recommend not to pipe some script from a random site in a stack overflow answer, to your shell. – eggonlegs Dec 12 '16 at 15:58