Date arithmetic in Unix shell scripts

前端 未结 14 1510
生来不讨喜
生来不讨喜 2020-11-27 22:29

I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs.

I\'m using a function to increment a day and another

相关标签:
14条回答
  • 2020-11-27 23:01

    I have bumped into this a couple of times. My thoughts are:

    1. Date arithmetic is always a pain
    2. It is a bit easier when using EPOCH date format
    3. date on Linux converts to EPOCH, but not on Solaris
    4. For a portable solution, you need to do one of the following:
      1. Install gnu date on solaris (already mentioned, needs human interaction to complete)
      2. Use perl for the date part (most unix installs include perl, so I would generally assume that this action does not require additional work).

    A sample script (checks for the age of certain user files to see if the account can be deleted):

    #!/usr/local/bin/perl
    
    $today = time();
    
    $user = $ARGV[0];
    
    $command="awk -F: '/$user/ {print \$6}' /etc/passwd";
    
    chomp ($user_dir = `$command`);
    
    if ( -f "$user_dir/.sh_history" ) {
        @file_dates   = stat("$user_dir/.sh_history");
        $sh_file_date = $file_dates[8];
    } else {
        $sh_file_date = 0;
    }
    if ( -f "$user_dir/.bash_history" ) {
        @file_dates     = stat("$user_dir/.bash_history");
        $bash_file_date = $file_dates[8];
    } else {
        $bash_file_date = 0;
    }
    if ( $sh_file_date > $bash_file_date ) {
        $file_date = $sh_file_date;
    } else {
        $file_date = $bash_file_date;
    }
    $difference = $today - $file_date;
    
    if ( $difference >= 3888000 ) {
        print "User needs to be disabled, 45 days old or older!\n";
        exit (1);
    } else {
        print "OK\n";
        exit (0);
    }
    
    0 讨论(0)
  • 2020-11-27 23:02

    Assuming you have GNU date, like so:

    date --date='1 days ago' '+%a'
    

    And similar phrases.

    0 讨论(0)
提交回复
热议问题