Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

How do I set a variable to the output of two commands in Bash

I read How do I set a variable to the output of a command in Bash? and tried to do that twice:

TESTVAR=$(echo 1) $(echo 2)`
TESTVAR="$(echo 1)" "$(echo 2)"
TESTVAR=`echo 1` `echo 2`

All three options fail with -bash: 2: command not found.

Bash version 4.3.30

question from:https://stackoverflow.com/questions/65831931/how-do-i-set-a-variable-to-the-output-of-two-commands-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that bash runs the two commands, captures their outputs, and then substitutes that to produce TESTVAR=1 2. That assigns 1 to TESTVAR and tries to run 2. Apparently, there's no executable called "2" on my PATH.

The second attempt with quotes came close, but the quotes don't belong to the individual substiturions. You need a single pair:

TESTVAR="$(echo 1) $(echo 2)"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...