Uvuvwevwevwe
Uvuvwevwevwe

Reputation: 1041

How to replace back-slash with nothing in Bash script

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

  1. // replace for every
  2. \\ back slash
  3. / with
  4. nothing

However, I got the error

2019\12\04/\/: No such file or directory

What did I do wrong here?

Upvotes: 0

Views: 1567

Answers (3)

dash-o
dash-o

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

Charles Duffy
Charles Duffy

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

KamilCuk
KamilCuk

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

Related Questions