簡體   English   中英

BASH:如果目錄中的文件數大於或等於2,則需要運行if語句

[英]BASH: If statement needed to run if number of files in directory is 2 or greater

我有以下BASH腳本: http : //pastebin.com/CX4RN1QW

僅當目錄中的文件數為2或更大時,我才希望運行腳本中的兩個部分。 它們在## Begin file test here標記為## Begin file test here## End file test.

我對腳本非常敏感,我不希望更改任何其他內容,即使它可以簡化它。

我努力了:

if [ "$(ls -b | wc -l)" -gt 1 ];

但這沒有用。

您可以使用glob來檢查目錄中是否存在文件,而不是使用外部ls命令:

編輯我想念您正在尋找> 2個文件。 更新。

shopt -s nullglob # cause unmatched globs to return empty, rather than the glob itself
files=(*) # put all file in the current directory into an array
if (( "${#files[@]}" >= 2 )); then # since we only care about existence, we only need to expand the first element
   ...
fi
shopt -u nullglob # disable null glob (not required)

您需要在其中使用ls -1才能使其工作,因為-b不會使它每行打印一項。 或者使用find ,因為默認情況下會這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM