请教格式化字符串中%d与%y在Shell命令中的含义
%y (from stat) and %d (from printf) Hey there! Let's clear up the confusion around these two symbols you encountered—they belong to different tools, so that's probably why your initial searches didn't turn up the right info.
1. What does %y mean in stat -c %y?
First off, your command man stat | egrep -o "%y" didn't return anything because % is a special character in regular expressions. You'd need to escape it (like egrep -o "\%y") or use fixed-string matching (fgrep "%y" instead) to find it in the man page.
In reality, %y is a format specifier for the stat command, used to control what output it produces. Specifically:
%yprints the last modification time of the file in a human-readable format (e.g.,2024-05-20 14:30:45.123456789 +0200).- If you wanted the modification time as a Unix timestamp (seconds since epoch), you'd use
%Yinstead.
Your original command stat -c %y "$1"/* is fetching the modification time for every file in the directory passed as the first argument, then cut -c 12-13 extracts the hour portion (since the time starts at character 12 in that format).
2. What does %d mean in printf "Total files = %d"?
%d has nothing to do with Bash itself—it's a format placeholder for the printf command. In printf syntax:
%dis used to print a decimal integer (whole number). When you runprintf "Total files = %d\n" $count, it takes the value stored in the$countvariable (which should be an integer) and inserts it into the string where%dis.
For example, if count=10, this command would output:
Total files = 10
If you want to learn more about printf format specifiers, check out man printf—it lists all placeholders like %s (strings), %f (floats), etc.
Quick Pro Tips
- To see all format specifiers for
stat, open its man page (man stat) and look for the FORMAT section—you'll find every%-based option there. - For
printfdetails,man printfis your go-to resource, since it's part of GNU coreutils (Bash does have a built-inprintf, but it follows the same standard syntax).
内容的提问来源于stack exchange,提问作者Wizard

