The shell script deletes the folder N days ago. The date commands on linux and mac are different,
Background:
Every day you build things and put them in different folders by date. For example, today's construction is put in, tomorrow's will be put in, and so on. After a long time, you need a script to delete the folder N days ago. (N = 7 in this example, that is, the build one week ago is deleted ).
The following code is available for linux:
#! /Bin/bashhistoryDir = ~ /Test/today = $ (date + % Y-% m-% d) echo "--------- today is $ today -----------" tt = 'date-d last-week + % Y-% m-% d' echo "next is to delete release before $ tt" tt1 = 'date-d $ tt + % s' # delete folders smaller than this value # echo $ tt1 for file in $ {historyDir} * do if test-d $ file then name = 'basename $ file' # echo $ name curr = 'date-d $ name + % s' if [$ curr-le $ tt1] then echo "delete $ name -------" rm- rf $ {historyDir }$ {name} fi fidone
Note:
1, historyDir = ~ /Test/must be followed by/; otherwise, for file in $ {historyDir} * will not match when the folder is traversed.
2. in linux, use today =$ (date + % Y-% m-% d) to obtain a date in the format.
tt1=`date -d $tt +%s`
Returns the timestamp of the integer. Of course, you can also use $ (date + % s) to get the timestamp directly, without conversion, however, the date is the default format conversion timestamp of year, month, hour, minute, and second.
PS: Not on MAC.
3. in linux, date-d last-week + % Y-% m-% d is used to obtain the date from the previous week.
PS: No rows under MAC.
4. if test-d $ file is used to determine whether a folder exists, and-f is used to determine whether a file exists.
name=`basename $file`
Get the folder name, and convert the name (that is, the date) to the timestamp comparison.
Code on MAC
#! /Bin/bashhistoryDir = ~ /Test/today = $ (date + % Y-% m-% d) echo "--------- today is $ today -----------" today1 = 'date-j-f % Y-% m-% d $ today + % s' # echo "today1 = $ today1 "# calculate the time tt = $ (date-v-7d + % Y-% m-% d) a week ago) echo "next is to delete release before $ tt" tt1 = 'date-j-f % Y-% m-% d $ tt + % s' # on linux, 'date -d $ tt + % s' # delete folders smaller than this value # echo $ tt1 for file in $ {historyDir} * do if test-d $ file then name = 'basename $ file 'echo $ name curr = 'date-j-f % Y-% m-% d $ name + % s' if [$ curr-le $ tt1] then echo "delete $ name "rm-rf $ {historyDir }$ {name} fi fidoneecho" -------------- end ---------------"
There are two differences with linux:
1. When the string time is converted into an integer timestamp, the mac should be as follows:
today1=`date -j -f %Y-%m-%d $today +%s`
2. The mac date obtained 7 days ago should be as follows:
tt=$(date -v -7d +%Y-%m-%d)
Related links:
1, http://willzh.iteye.com/blog/459808
Http://apple.stackexchange.com/questions/115830/shell-script-for-yesterdays-date 2