Try this instead:
Bash:
#!/bin/sh
DAY=$(date +%m%d%H%M)
Location=$(pwd | grep -o '[^/]*$' | tr -d '\n')
echo "This is a test $Location and $DAY" > file_"$Location"_"$DAY".log
The problem was, the shell thought that the parameter was called
$Location_
NOT
$Location
. And because
$Location_
does not exist - it has no value, so nothing is substituted into the file-name for the redirected file, so you only get the filename written out as
file_$DAY.log
.
When de-referencing the values of variables, they should be always be enclosed in double quotes, this prevents a number of problems like word splitting. Everything between the quotes is treated as a single word, or a single string - including any white-space characters. Without the quotes, any white-space could cause the string to be split into separate words.
In the
echo
command, we have enclosed both parameters in a single set of double-quotes along with the rest of the message to output to the screen. This is absolutely fine because the variables are separated from other text by spaces, so they get treated as separate entities when the variable substitution is performed and the values of the variables are substituted into the double-quoted string.
In the file-redirection, we have used double-quotes around each of the variables, this helps the shell to correctly interpret that the underscore is a literal character that separates the substituted values from the two variables. It's not a part of the
$Location
variable-name.
Also, with your
date
command - I've replaced the back-ticks with a shell-substitution.
Back-ticks and shell-substitutions do pretty much the same thing, but shell-substitutions are the preferred method according to the POSIX standard. Using back-ticks can get messy for more complicated commands. The shell-substitution syntax is a lot cleaner and prevents a number of other potential problems too!
I hope this makes sense!