Home > Net >  Why does command substitution work in example 2 but not example 1?
Why does command substitution work in example 2 but not example 1?

Time:12-06

EXAMPLE 1: from BASH terminal (doesn't work):

$(date | sed -r 's/[ ]{2,}/ /gi')

EXAMPLE 2: from a BASH shell script (does work):

ECHO_DATE=$(date | sed -r 's/[ ]{2,}/ /gi')

CodePudding user response:

In the first example, you're running the result of the evaluation in the $(). Right now, that result starts with Mon, so you'll get a command not found error. In the second, you're assigning the result to a variable. To see it immediately, you can do:

echo "$(date | sed -r 's/[ ]{2,}/ /gi')"

But you also don't need to evaluate an extra step at all:

date | sed -r 's/[ ]{2,}/ /gi'

I would also recommend checking out man date, because date has builtin formatting options.

  • Related