Basic script to get directory name and time.

Andy5441

New Member
Joined
Jun 15, 2020
Messages
5
Reaction score
3
Credits
61
I wrote this shell script

# !/bin/sh -x
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
pwd is /home/some/where/in/mydirectory
Why I did not see $location in the file name but can see it in the log ? The log file only show file_$DAY.log NOT file_$Location_$DAY.log
cat file_12161517.log
This is a test mydirectory and 12161517

What did I do wrong ? Thanks
 


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!
 
Last edited:

Members online


Latest posts

Top