bash shell date usage (normal in bash and for bash parameter)
date function in bash shell script is really powerful.
Notice:
1. no space after the "+" to define the format.
2. If use on a bash cron job cmd, then "\" is need to escape %.
It recognize the datetime in many different format and can be convert to almost any format you need.
1. change YYYYMMDD to YYYY-MM-DD
olddate="20121010"
newdate=$(date -d"${olddate}" +%Y-%m-%d)
2. want to get the date n days before a fixed date
olddate="20121010"
days=n
newdate=$(date -d"${olddate} - ${days} days" +%Y-%m-%d)
3. want to get the date n days after a fixed date
olddate="20121010"
days=n
newdate=$(date -d"${olddate} + ${days} days" +%Y-%m-%d)
4. n month before
newmonth=`date +%Y%m -d "$n months ago"`
5. Use as the bash parameters
Be aware that the "%" needs to be escaped
~$bash example.sh `date +\%Y-\%m-\%d -d "3 days ago"`
or
~$bash example.sh $(date +\%Y-\%m-\%d -d "3 days ago")
6. Get number of days of a month
daysofmonth=`cal $(date +"%m %Y") | awk 'NF {DAYS = $NF}; END {print DAYS}'`
7. Get the first day of a month:
First got the current day as the parameter for "-d".
firstdaymonth=`date +%Y-%m-%d -d "-1 month -$(($(date +%d)-1)) days"`
lastday=`date +%Y-%m-%d -d "-$(date +%d) days"`
8. Use the date with crontab
exclude a date:
[ $(date +\%d) = 03 ] || cmd
or
[ "$(date +\%d)" = "03" ] || cmd
exclude several dates:
[ `date +\%d` -gt 3 ] && cmd
tips: both $() or `` works when get the date
Notice:
1. no space after the "+" to define the format.
2. If use on a bash cron job cmd, then "\" is need to escape %.
It recognize the datetime in many different format and can be convert to almost any format you need.
1. change YYYYMMDD to YYYY-MM-DD
olddate="20121010"
newdate=$(date -d"${olddate}" +%Y-%m-%d)
2. want to get the date n days before a fixed date
olddate="20121010"
days=n
newdate=$(date -d"${olddate} - ${days} days" +%Y-%m-%d)
3. want to get the date n days after a fixed date
olddate="20121010"
days=n
newdate=$(date -d"${olddate} + ${days} days" +%Y-%m-%d)
4. n month before
newmonth=`date +%Y%m -d "$n months ago"`
5. Use as the bash parameters
Be aware that the "%" needs to be escaped
~$bash example.sh `date +\%Y-\%m-\%d -d "3 days ago"`
or
~$bash example.sh $(date +\%Y-\%m-\%d -d "3 days ago")
6. Get number of days of a month
daysofmonth=`cal $(date +"%m %Y") | awk 'NF {DAYS = $NF}; END {print DAYS}'`
7. Get the first day of a month:
First got the current day as the parameter for "-d".
firstdaymonth=`date +%Y-%m-%d -d "-1 month -$(($(date +%d)-1)) days"`
lastday=`date +%Y-%m-%d -d "-$(date +%d) days"`
8. Use the date with crontab
exclude a date:
[ $(date +\%d) = 03 ] || cmd
or
[ "$(date +\%d)" = "03" ] || cmd
exclude several dates:
[ `date +\%d` -gt 3 ] && cmd
tips: both $() or `` works when get the date
Comments
Post a Comment