Reputation: 1041
In a bash script, I would like to get the current date in the format of YYYY\mm\dd
.
Then I want to remove the back slash \
and store the result in a variable, FOO
.
My code is
FOO=$($(date +'%Y\%m\%d')//\\/)
echo "$FOO"
The literal words for //\\/
are
//
replace for every\\
back slash/
withHowever, I got the error
2019\12\04/\/: No such file or directory
What did I do wrong here?
Upvotes: 0
Views: 1567
Reputation: 14452
The script has two nested '$(' construct. One should do the work. The second one should be ${}
to remove the unwanted \
YMD=$(date +'%Y\%m\%d')
FOO=${YMD//\\/}
echo "$FOO"
The error message is triggered when the formatted date is forced as a command by the outside '$('. Also note that ${}
can not be nested unlike $()
, they REQUIRE a variable name.
Side question - why add \
, when you do not need it ?
Upvotes: 2
Reputation: 295490
Parameter expansions don't nest; you need to do them as separate steps.
foo=$(date +'%Y\%m\%d')
foo=${foo//'\'/}
echo "$foo"
Note the use of lower-case variable names -- this is per POSIX-defined convention, which specifies all-uppercase names as used for variables meaningful to the shell or operating system, and reserves other names for application use.
Upvotes: 2
Reputation: 141155
The ${var//\\/}
uses {
}
braces and it is a variable expansion, it needs a variable to expand.
You can:
FOO=$(date +'%Y\%m\%d')
FOO=${FOO//\\/}
Upvotes: 2