0

I want to create a filename for redirecting output to.

eg:

ls -lash > $filename

All the variables are set.. So far I've tried the following:

filename=`echo $site . "_location_" . $address . "_" .  $timestamp . ".txt"` 

filename=$site . "_location_" . $address . "_" .  $timestamp . ".txt" 

filename="$site_location_$address_$timestamp.txt" 

None have worked.. How do I get a file named like:

site1_location_northeast_071218142325.txt

Thanks

Tom
  • 1,436
  • 24
  • 50
  • The dot (`.`) is the string concatenation operator in PHP, not in shell script. – axiac Dec 07 '18 at 14:36
  • Side note: As answers have pointed out, you don't need command substitution here. When you do though, use the modern form `$(command)` rather than `\`command\``. `$()` is much easier to read and can be conveniently nested. – Soren Bjornstad Dec 07 '18 at 17:28

2 Answers2

2

Just use string interpolation.

filename="${site}_location_${address}_${timestamp}.txt"

The braces prevent the _ from being treated as part of the preceding parameter name (or more precisely, they delimit the enclosed string as the parameter name).

chepner
  • 497,756
  • 71
  • 530
  • 681
2

All you need is:

filename="${site}_location_${address}_${timestamp}.txt" 

The curly braces around variable names help Bash know you want to replace the value of variables $site and $address. Otherwise, because _ is a valid character in variable names, it thinks you want the use the variables $site_location_ and $address_ (that do not exist.)

axiac
  • 68,258
  • 9
  • 99
  • 134