
我有一個 bash 腳本,需要將其從 linux 轉換為 FreeBSD,但我顯然太愚蠢了,無法以正確的方式閱讀手冊頁面。
該腳本有一行:
date +%d -r "$file"
在linux下工作得很好,但只是給出
date: illegal time format
在 FreeBSD 上。
這Linux 手冊頁表示-r
用於指定引用檔:
-r, --reference=FILE
display the last modification time of FILE
這裡令我困惑的是FreeBSD 手冊頁包含此開關的相同用法,但也提供了替代開關:
-r seconds
Print the date and time represented by seconds, where seconds is
the number of seconds since the Epoch (00:00:00 UTC, January 1,
1970; see time(3)), and can be specified in decimal, octal, or
hex.
-r filename
Print the date and time of the last modification of filename.
顯然,上述錯誤訊息是由於期望 UNIX 時間戳記作為開關參數-r
而不是提供的檔案名稱而導致的。
我不明白的是,我應該如何清楚地表明我想使用開關的第二種解釋-r
。如果它應該從呼叫的上下文中推斷出來,我對如何提供此上下文感到困惑。
誰能向我解釋一下,我應該如何告訴日期實用程序,-r
我想在這裡使用開關的哪種用例?
答案1
看起來這個-r
用法只出現在來源中2015 年 5 月 7 日。也許您的版本還沒有這樣做?
Revision 282608 - (view) (download) (annotate) - [select for diffs]
Modified Thu May 7 20:54:38 2015 UTC (12 months, 1 week ago) by delphij
date(1): Make -r behave like GNU's version when the option can not be
interpreted as a number, which checks the file's modification time and
use that as the date/time value.
答案2
該腳本有一行:
日期 +%d -r "$file"在linux下工作得很好,但是…
....在 FreeBSD/PC-BSD 上將會失敗,因為該date
命令解析其命令列getopt()
且選項必須嚴格位於參數之前。格式字串+%d
是一個參數,必須跟在-r
選項後面;否則-r
不被識別為選項,而是被視為(無效)參數。請注意,手冊頁上的命令概要會date
依此順序顯示它們。
是的,僅當無法將date
選項參數解碼為數字時,才將其視為檔案名稱。-r
是的,當檔案名稱是數字時,這是一個問題。 ☺
讀取檔案/目錄的最後修改時間而不用擔心其名稱是否碰巧類似於數字的更好方法是命令stat
......如果它本身沒有重大困難的話。
案例“`uname`” Linux) stat -c '%y' -- "$1"|cut -c9-10 ;; *BSD) stat -f '%Sm' -t '%d' -- "$1" ;; 埃薩克