-   Linux - General (
-   -   Question about variables in BASH scripts (

gimpy530 11-19-2009 09:29 PM

Question about variables in BASH scripts
A few random questions:

What is the difference between:

VAR=`date +%F_%H%M%S`


VAR=$(date +%F_%H%M%S)

Also, this question may be related:

If the output of a command is set as a variable in the beginning of the script, and later during that script the output of the original command that became the variable changes, does the variable change when it is called upon? In other words, when the command for the variable is ran to set the variable, is it simply "remembered" and static for the remainder of the script, or would that command be ran every time that variable is called in the script?


1 #!/bin/sh
2 CURDATE=`date +%m-%d-%y`
3 blah blah blah
4 somecommand 1> $CURDATE.stdout

Assume line two happens on Tuesday, but the script does not get to line 4 until the next day, Wednesday. Would that stdout file have the date of Tuesday even though it happened on Wednesday, or would the date command within the $CURDATE variable be re-ran when it is called upon and have the date of Wednesday?

david1941 11-19-2009 09:37 PM

There is no difference in how the ` ` or $() works. I prefer the second form as it is easier to see with my failing eyes. Once the variable is assigned, it stays the same until reassigned. 11-19-2009 09:39 PM

var=`command` and var=$(command) are the same.

however i feel it's better practice to use $(), it keeps the script neater.

re. your 2nd question, i think the variable is set according to the output of that specific instance. if the output of the same command changes later on in the script, unless you re-set the variable, i don't think it will change.

could be wrong here....

GrapefruiTgirl 11-19-2009 09:43 PM

The above link was given me by catkin earlier today; it explains a few reasons why $() is better than using `backticks`.

As to the 2nd question, the answer is: the variable will remain the same, and does not get reassigned, so your example would still contain "Tuesday" unless you re-ran line#2 on Wednesday or another day.


gimpy530 11-19-2009 09:53 PM

Three answers that agree with each other. Awesome.

Of course this proves the concept of the first question:

echo `date +%r`
echo $(date +%r)

That link makes it very clear, and btw GrapefruiTgirl, the first question came from seeing another one of your posts a few minutes ago.

GrapefruiTgirl 11-19-2009 10:02 PM

:) It's always good when a questions answers are in agreement-- something that doesn't always happen!

Kind regards,

All times are GMT -5. The time now is 01:32 PM.