LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash script and two variables (https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-and-two-variables-4175524835/)

ASTRAPI 11-08-2014 06:23 PM

Bash script and two variables
 
Hi

I use a bash script:

Code:

DATE="$(/bin/date +%d-%m-%Y)"
TIME="$(/bin/date +%H-%M)"
/bin/tar -czf myfiles_$DATE_Time_$TIME.tgz file.zip

And i want on the outpout to have inside the date and time the word Time so i will not get all numbers together....

like this:

Code:

myfiles_09-11-2014_Time_15-30.tgz
But it seems that it doesn't like the _Time_ as it is not working with it there and when i remove it is fine...

How can i do this?

Thanks

grail 11-09-2014 03:36 AM

Your issue is that an underscore is part of valid variable name, hence when you pass the string to tar it looks like:
Code:

myfiles_$DATE_Time_$TIME.tgz
As you can see from the colours, you have no variable called $DATE_Time_

When you have additional parts that need to be attached though, bash has the curly brace enclosure to assist with sectioning off the variable names.
So you can use:
Code:

myfiles_${DATE}_Time_$TIME.tgz
Now this will only look for $DATE and will append _Time_.

The curly brace enclosure can actually be used around all variables all the time. It does make your code cleaner however to only use them when required.

pan64 11-09-2014 04:59 AM

you can also write:
Code:

NAME="$(/bin/date +myfiles_%d-%m-%Y_Time_%H-%M)"
/bin/tar -czf $NAME.tgz file.zip


ASTRAPI 11-09-2014 07:41 AM

Thanks both of you :)

grail 11-09-2014 08:47 AM

Please remember to mark as SOLVED once you have a solution

suicidaleggroll 11-09-2014 08:50 AM

As a quick note on convention, all caps is generally reserved for environment variables. It's somewhat frowned upon to use names in all caps for regular variables in a script, because it can lead to confusion. Instead, regular variables should be lower case or mixed case.

Beryllos 11-09-2014 09:36 PM

You could also set the variables apart with quotation marks, for example:
Code:

echo "$DATE"_Time_"$TIME"
09-11-2014_Time_22-33



All times are GMT -5. The time now is 07:53 AM.