2014-07-08 50 views
1

我很新的Linux腳本&正在試圖建立一個簡單的循環,其將:Bash腳本 - 如何保持循環查找命令直到找到文件/ s?

  1. 要求用戶提供文件名
  2. 搜索特定的目錄文件
  3. 如果沒有找到任何文件,要求用戶重新輸入到文件名
  4. 如果找到的文件,移動到腳本的下一步

這是我迄今爲止,但它不是循環(即沒有找到文件時,它不會要求用戶重新輸入文件名。 )

#!/bin/bash 
read -p "Enter file name: " file 
find /directory/ -name "$file" -print 
while [ "$?" -ne 0 ]; do 
     read -p "File not found. Please re-enter file name: " file 
     find /directory/ -name "$file" -print 
done 
echo "rest of script etc" 

任何幫助表示讚賞! :)

+0

'find'在錯誤時返回非0,如果沒有找到文件則返回非0。請參閱[this](http://serverfault.com/a/225827)以獲得簡單的修復。另外,考慮在你找到一個匹配後,在你的find命令中加入'-quit'來停止遍歷。 – BroSlow

回答

-1

最簡單,最簡便的方式可能是這樣的:

# Loop until user inputted a valid file name 
while true ; do 
    # Read input (the POSIX compatible way) 
    echo -n "Enter file name: " 
    read file 

    # Use find to check if the file exists 
    [ $(find /etc -type f -name "$file" 2>/dev/null | wc -l) != "0" ] && break 

    # go to next loop if the file does not exist 
done 

echo "Ok, go on here" 
+0

這與'find/directory -name「$ file」'會做的事情不一樣。 – kojiro

+0

感謝您的建議hek2mgl,但是@kojiro表示這不會做同樣的事情。 我需要使用find命令,並且只要命令不返回任何東西就可以循環。 – user3792362

+0

暗示本來就夠了,很難從問題中得出結論。特別是在專注於需求的文本表示時。感謝@kojiro的反對票。幹得好! – hek2mgl

1

要做到這一點最簡單的方法可能是使用globstar(可使用bash 4)

#!/bin/bash 
shopt -s globstar 
while true; do 
    read -p "Enter file name: " file 
    for f in /directory/**/"$file"; do 
     echo "$f" 
     break 2 # escape both loops 
    done 
    echo "'$file' not found, please try again." 
done 
echo "rest of script etc" 

它也可以與find做,但稍微惱人,因爲你不能使用標準的UNIX退出狀態:

#!/bin/bash 
read -p "Enter file name: " file 
found=$(find /directory/ -name "$file" -print -quit) 
while [[ -z $found ]]; do 
    read -p "File not found. Please re-enter file name: " file 
    found=$(find /directory/ -name "$file" -print -quit) 
done 
echo "$found" 
echo "rest of script etc" 

通常我不會推薦分析find的輸出,但在這種情況下,我們只關心是否有任何輸出。

+0

你應該明確地啓用globstar,因爲它不是默認的。 –

+0

@thatotherguy感謝捕捉。 – kojiro