4

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

0

6 Answers 6

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

There's no point using echo like that -- it doesn't add anything since you're just giving it a string and then capturing that same string again. You can just do x="$(date +%Y) $(date +%m)"
@John Bartholomew, you're right, it's a habit because I tend immediately to pipe echo to sed, etc.
5

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

1 Comment

You have a typo/copy-paste error: you're still using $y in your second example.
1

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.

Comments

0

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

Comments

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

Note the reverse accent (´)

2 Comments

Except that you're using the wrong character. And $() is preferred.
Thanks, while I answer the question I was on Windows.
0
echo `date +%Y` `date +%m`

And to make the minimum change to the OP:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.