Print a file's last modified date in Bash

后端 未结 10 2166
难免孤独
难免孤独 2020-11-29 18:01

I can\'t seem to find how to print out the date of a file. I\'m so far able to print out all the files in a directory, but I need to print out the dates with it.

I

10条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 18:35

    On OS X, I like my date to be in the format of YYYY-MM-DD HH:MM in the output for the file.

    So to specify a file I would use:

    stat -f "%Sm" -t "%Y-%m-%d %H:%M" [filename]
    

    If I want to run it on a range of files, I can do something like this:

    #!/usr/bin/env bash
    for i in /var/log/*.out; do
      stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
    done
    

    This example will print out the last time I ran the sudo periodic daily weekly monthly command as it references the log files.


    To add the filenames under each date, I would run the following instead:

    #!/usr/bin/env bash
    for i in /var/log/*.out; do
      stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
      echo "$i"
    done
    

    The output would was the following:

    2016-40-01 16:40
    /var/log/daily.out
    2016-40-01 16:40
    /var/log/monthly.out
    2016-40-01 16:40
    /var/log/weekly.out
    

    Unfortunately I'm not sure how to prevent the line break and keep the file name appended to the end of the date without adding more lines to the script.


    PS - I use #!/usr/bin/env bash as I'm a Python user by day, and have different versions of bash installed on my system instead of #!/bin/bash

提交回复
热议问题