0

Please see the below shell script:

#!/bin/bash
echo "Enter the date in (YYYY-MM-DD) format: "
read dt
i=00
echo "/opt/log-$dt_$i"

Expected Output :

Enter the date in (YYYY-MM-DD) format:
2020-06-18
/opt/log-2020-06-18_00

But Getting the below output:

Enter the date in (YYYY-MM-DD) format:
2020-06-18
/opt/log-00

Please suggest?

2 Answers2

1

You need to change your echo line to this:

echo "/opt/log-${dt}_${i}"

Explanation:

An _ (underscore) is a valid character in a variable name, so bash is looking for $dt_ and $i. Since $dt_ is not defined, it doesn't print it. Bash provides the alternate variable syntax using ${} to explicitly isolate the variables when performing string interpolation like this.

Matt Jeffery
  • 41
  • 1
  • 4
  • The 2nd example is actually bad: you are actually *unquoting* the `dt` variable, which exposes you to word splitting and globbing. Especially since we're directly dealing with user input that you can't trust. – glenn jackman Jun 18 '20 at 19:30
  • 1
    Yes, good point. It was kind of an afterthought. I've removed it from my answer – Matt Jeffery Jun 18 '20 at 19:53
0

Like this:

echo "/opt/log-${dt}_$i"
#               ^  ^
#       curly brackets mandatory here

This is because you have to separate the variables with _ that could be part of any variables.

Which editor do you use ? For me in , it's clear:

enter image description here

Versus:

enter image description here

(the underscore become white)

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223