
我想檢查最新檔案的大小是否大於 2 MB:
test $(ls -st | head -n2 | tail -n1 | awk '{print $1}') -gt 2097152 && echo "true"
有沒有更有效或更優雅的方法來做到這一點?
我嘗試進一步將 awk 的輸出透過管道傳輸到
| test {} -gt 2097152
但得到
bash: 測試: {}: 需要整數表達式
然後
| test {}>"2097152"
產量總是“true”,所以我想出了這個結構
test $(...) -gt 2097152
答案1
可能有比ls
獲取最新文件更好的方法,但是您所做的大部分操作都可以在 awk 中完成:
ls -st | awk 'NR == 2 && $1 > 2097152 {print "true"}'
NR == 2
- 在第二行$1 > 2097152
- 當第一列大於2097152時
答案2
和zsh
:
set -- *(.om[1]) *(N.L+2097152om[1])
if [[ $1 = $2 ]]; then
printf '%s\n' "The apparent size of the newest non-hidden regular file in the current" \
"directory ($1) is strictly greater than 2MiB."
fi
如果要包含隱藏目錄,請新增D
至兩個 glob 限定符。如果您想考慮非常規檔案(目錄、符號連結、裝置...),請刪除.
這個想法是擴展這兩個範圍:
.
非隱藏常規 ( ) 檔案列表,o
依m
修改時間排序,僅限一個 ([1]
)。- 相同,但僅限於
L
長度嚴格大於 (+
)的檔案2097152
(但啟用N
ullGlob,因此如果沒有匹配項,這不是致命錯誤)。
我們的條件是指兩個 glob 都擴展到同一個檔案。
請注意ls -s
, 不報告文件的大小,而是報告其磁碟使用情況(以 512 位元組單位的數量或 KiB 或其他單位表示,取決於實施ls
和/或環境)。ls
報告其中的檔案大小長的輸出格式(ls -l
或ls -n
(或-o
/-g
與某些實作))。
另一種選擇是使用 的zsh
內建stat
函數來取得最新檔案的大小(或磁碟使用情況):
zmodload zsh/stat
if
stat -LH s -- *(.om[1]) &&
((s[size] > 2097152))
then
printf '%s\n' "The apparent size of the newest non-hidden regular file in the current" \
"directory ($1) is strictly greater than 2MiB."
fi
或者:
zmodload zsh/stat
if
stat -LH s -- *(.om[1]) &&
((s[blocks] > 2097152))
then
printf '%s\n' "The newest non-hidden regular file in the current directory" \
"($1) uses more than 2097152 512-byte units of disk space."
fi
(換句話說,它的磁碟使用量超過1GiB)