简体   繁体   中英

Bash variable mystery

So at work we use an accounting system and at the end of the month we have to modify a script for the previous month and specify a new name for the log that's printing out. Since I'm fairly lazy and would rather spend my time learning something new than repeating the same task over again I decided I wanted to write the script to do it all for me and set it as a cron job. Since I just started this job and I'm new to Bash programming in general I decided to research a little and found everything I needed to do the job and came up with this.

#!/bin/bash
month= $(echo $(date --date="last month" +%b))
year=$(echo $(date +%Y))
echo $(date --date="last month" +%Y-%m-%d)
echo $(date --date="yesterday" +%Y-%m-%d)
echo $(date --date="last month" +%b)
echo garuda-summary-$month$year.log;

and it prints out this

test.sh: line 2: Apr: command not found
2011-04-02
2011-05-01
Apr
computer-summary-2011.log

So I played with it some more and got this one to work. But it's ugly and I want to know why it didn't work before. Thanks in adv

#!/bin/bash
month= $(echo $(date --date="last month" +%b))
year=$(echo $(date +%Y))
echo $(date --date="last month" +%Y-%m-%d)
echo $(date --date="yesterday" +%Y-%m-%d)
echo $(date --date="last month" +%b)
echo garuda-summary-$(date --date="last month" +%b)$year.log;
test.sh: line 2: Apr: command not found

is because you have a space after your "=" when assigning to month. This space makes bash think that Apr (the output of $(echo $(date --date="last month" +%b))) is a command you want to call.

This will also result in month not being set in the shell, because specifying a command on the same line as a variable assignment tells bash only to use this variable value when calling the specified command.

First of all, you don't need to do everything in sub-shells through echo. This should be the equivalent, and more easy to work with:

#!/bin/bash
month=`date --date="last month" +%b`
year=`date +%Y`
date --date="last month" +%Y-%m-%d
date --date="yesterday" +%Y-%m-%d
date --date="last month" +%b
echo garuda-summary-$month$year.log

You could dispense with the $(...) stuff by doing:

year=`date +%Y`
month=`date --date='last month'`

and so on, which should improve legibility somewhat.

As well, you may want to check what happens when the current month is January of any year. You'll generate "December 2011" for your dates, rather than "December 2010".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM