Want to assign the result of the command echo ^`da

2019-08-19 03:29发布

echo ^`date`
^Wed Jan 21 05:49:37 CST 2015

deeps=`echo ^`date``
echo $deeps

Actual Result:

^date

Expected Result :

^Wed Jan 21 05:49:37 CST 2015

Need help on this

标签: linux bash
3条回答
小情绪 Triste *
2楼-- · 2019-08-19 04:02

Use a backtick, or use Command substitution. Like

# Shell command substitution.
echo ^$(date)

or

# backticks.
deeps=`date`
echo ^$deeps

Both output (the requested)

^Wed Jan 21 08:16:01 EST 2015
查看更多
放荡不羁爱自由
3楼-- · 2019-08-19 04:10

Try this method

deeps=^$(date)
echo $deeps

Output :

^Wed Jan 21 18:44:25 IST 2015

Backticks are horribly outdated and should not be used any more -- using $() instead will save you many headaches

查看更多
姐就是有狂的资本
4楼-- · 2019-08-19 04:19

Simply because neither of the other (correct) answers actually explain the problem I'm adding another answer.

tl;dr Compare the backtick version to the $() version

The difference between

echo ^`date`

and

deeps=`echo ^`date``

is how many backticks are on the line and how the shell is parsing the line.

echo ^`date`

has a single pair of backticks and the shell parses it as (where the [] are marking "parts" of the line)

[echo] [^][`date`]

The

`date`

bit is then expanded via Command Substitution and so the line becomes

[echo] [^Wed Jan 21 05:49:37 CST 2015]

and then echo spits out the desired ^Wed Jan 21 05:49:37 CST 2015.

This line however

deeps=`echo ^`date``

is parsed as

[deeps][=][`echo ^`][date][``]

which you can already see is quite different and not correct (this happens because backticks cannot be nested for the record).

There are now two command substitutions on this line echo ^ and the empty string so the line becomes

[deeps][=][^][date][]

or with the "words" combined

[deeps][=][^date]

which then assigns ^date to deeps and echo $deeps then gets you ^date.

The $() form of command substitution, no the other hand, does nest and thus

deeps=$(echo ^$(date))

parses as

[deeps][=][$([echo] [^][$([date])])]

which properly runs both date and echo on the result. Though, as indicated in the other answers, the wrapping echo is not necessary as deeps=^$(date) will work just fine by itself.

查看更多
登录 后发表回答