0

My question is: can/how does one pipe compound commands ({ list; })? See Exhibit B. Exhibit A given for comparison's sake.

Exhibit A:

$ cat << EOF | xargs -n 1 echo           
foo
bar
qux
EOF
foo
bar
qux

Exhibit B:

$ cat << EOF | xargs -n 1 sh -c '{ var="$1"; echo "$var"; }'
foo
bar
qux
EOF


man sh:

-c               Read commands from the command_string operand
                            instead of from the standard input.  Special parame‐
                            ter 0 will be set from the command_name operand and
                            the positional parameters ($1, $2, etc.)  set from
                            the remaining argument operands.

1 Answer 1

5

The problem is that sh -c "something" needs another argument to become $0.

Your second example doesn't provide one, so the $1 is an empty string and you get your 3 blank lines. Use

cat << EOF | xargs -n 1 sh -c '{ var="$1"; echo "$var"; }' inlineshellscript
foo
bar
qux
EOF
food
bar
qux

In the script $0 is inlineshellscript. Normally I would use sh rather than inlineshellscript.

5
  • Or even simpler replace $1 by $0? Is there not a more elegant way to do this altogether? Commented Mar 15, 2022 at 5:54
  • 2
    @Erwann Do not replace $1 by $0. $0 has its purpose. See "pitfalls of treating $0 like $1" in this answer. Commented Mar 15, 2022 at 6:42
  • Or this, no? cat << EOF | xargs -I {} sh -c '{ var={}; echo "$var"; }' Commented Mar 15, 2022 at 9:36
  • 1
    @Erwann That solution is not great if there are "interesting" characters flowing down the pipe. There are not in this case of course, but in general it is best to let xargs split things rather than passing the characters to sh for it to interpret. Commented Mar 15, 2022 at 22:18
  • Would it not be better with $SHELL rather than sh, for consistency's sake? Also, sh is prone to "bad substitution". Commented Mar 17, 2022 at 7:01

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.