2014-04-20 107 views
2

你好,我目前正在嘗試在shell腳本中做一個if語句來檢測用戶是否沒有輸入任何文本。bash if語句檢測空白文本

我想如果用戶沒有輸入任何信息,或者他們輸入的內容無效,只有輸入正確的內容才能回顯並提醒。

這裏是我迄今爲止

echo "Current Address books " 
     ls -R |grep .txt 
     echo "--------------------------------------------------------------------" 
     echo -n "Please Enter the file you want to search in: " 
     read fileName 
     book=$fileName 
     if [ $fileName == "" ] 
     then 
       echo "Please Enter some Text " 
     else 
       echo -n "Please Enter a name: " 
     read search 

     grep -i $search $fileName 

     if grep -q "$search" "$fileName"; 
     then 
       echo "Found!" 
     else 
       echo "Not Found!" 
     fi 

fi 

回答

1

像這樣的事情?

#!/bin/bash 

echo "Current Address books " 
find -name '*.txt' -type f -exec bash -c 'printf "%s\n" "${@#./}"' _ {} + # Don't parse the output of ls 
printf -v spacesep "%68s"; printf '%s\n' "${spacesep// /-}" 
fileName= 
while [[ -z $fileName ]]; do 
    read -rep "Please Enter the file you want to search in: " fileName 
    book=$fileName # Is this variable used? 
    # Check that the file is really a file 
    if [[ -n $fileName ]] && [[ ! -f $fileName ]]; then 
     echo "Not a file, try again" 
     fileName= 
    fi 
done 
search= 
while [[ -z $search ]]; do 
    read -rep "Please Enter a name: " search 
    grep -i -- "$search" "$fileName" 
done 
if grep -qi -- "$search" "$fileName"; then 
    echo "Found!" 
else 
    echo "Not Found!" 
fi 

獎金。隨着-e切換到read,您具有讀線編輯功能,和文件上的製表符完成。 Wooow!

+0

你能解釋一下'printf'%s \ n「」${@#./}「'對我有什麼影響嗎? – user258030

+0

@ user258030如果沒有這個,'find'的輸出在每個文件名前都會有'。/'前導。代碼片段「${@#.//」「'擴展爲所有位置參數,前導'。/'被刪除。因此''printf'%s \ n「」${@#./}「每行打印一個位置參數,並刪除前面的'。/'。 –

+0

謝謝你是一個複雜而完美的解決方案,我需要什麼 – user258030

1

您可以使用-z "$var"符號:

if [ -z "$fileName" ]; then 
    echo "Please Enter some Text " 
else 
    read -p "Please Enter a name: " search 
fi 

檢查,如果字符串的長度爲零。

另外,您可以使用引用變量的名字做此項檢查:

if [ "$fileName" == "" ]; then 
    echo "Please Enter some Text " 
else 
    read -p "Please Enter a name: " search 
fi 
1

您可以使用一個控制迴路

until [ $fileName != "" ]; do 
    echo "Please Enter some Text " ; 
    read -p "Please Enter a name: " fileName ; 
done