Jon
Jon

Reputation: 739

Combine two shell commands into one output in shell

I am trying to combine 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

Upvotes: 4

Views: 4777

Answers (6)

rlibby
rlibby

Reputation: 6021

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

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

Upvotes: 6

puzzle
puzzle

Reputation: 6131

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

Upvotes: 5

DigitalRoss
DigitalRoss

Reputation: 146053

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

And to make the minimum change to the OP:

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

Upvotes: 0

Alberto
Alberto

Reputation: 1579

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

Note the reverse accent (´)

Upvotes: 0

Jeff Walden
Jeff Walden

Reputation: 7108

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.

Upvotes: 1

Tim
Tim

Reputation: 9172

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

Upvotes: 0

Related Questions