开发者

Combine two shell commands into one output in shell

I am trying to co开发者_运维技巧mbine multiple commands into a single output.

#!/bin/bash

x=$(date +%Y)
x=$($x date +m%)

echo "$x"

This returns

./test.sh: line 4: 2011: command not found


x=$(echo $(date +%Y) $(date +%m))

(Note that you've transposed the characters % and m in the month format.)


In the second line, you're trying to execute $x date +m%. At this point, $x will be set to the year, 2011. So now it's trying to run this command:

2011 date +%m

Which is not what you want.

You could either do this:

x=$(date +%Y)
y=$(date +%m)

echo "$x $y"

Or that:

x=$(date +%Y)
x="$x $(date +%m)"

echo "$x"

Or simply use the final date format straight away:

x=$(date "+%Y %m")
echo $x


Maybe this?

#!/bin/bash

x=$(date +%Y)
x="$x$(date +%m)"

echo "$x"

...also correcting what appears to be a transpose in the format string you passed to date the second time around.


Semicolon to separate commands on the command line.

date +%Y ; date +m%

Or if you only want to run the second command if the first one succeeds, use double ampersand:

date +%Y && date +%m

Or if you want to run both commands simultaneously, mixing their output unpredictably (probably not what you want, but I thought I'd be thorough), use a single ampersand:

date +%Y & date +%m


echo ´date +%Y´ ´date +m%´

Note the reverse accent (´)


echo `date +%Y` `date +%m`

And to make the minimum change to the OP:

x=$(date +%Y)
x="$x $(date +%m)"
echo "$x"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜