2016-05-03 68 views
0

我很迷惑我從腳本中獲得的錯誤,我試圖運行以暫停我的機器。我試圖在elif語句中使用正則表達式在特定時間段後暫停我的機器。bash在if語句中的正則表達式

#!/bin/bash 
echo "When would you like to suspend the machine?" 
read "sustime" 
if [ "$sustime" = "now" ] 
then 
    sudo pm-suspend 
elif [[ "$sustime" =~ [0-9]*[smhd] ]] 
then 
    time=`expr "$sustime" : '\([0-9]+)\)'` 
    ttype=`expr "$sustime" : '.*\([smhd]\)'` 
    sudo sleep $time$ttype ; sudo pm-suspend 
else 
    echo "Please enter either [now] or [#s|m|h|d]" 
fi 

如果我輸入5S的代碼不會對elif線工作,例如,該腳本的輸出是:

$ sh dbussuspend.sh 
When would you like to suspend the machine? 
5s 
dbussuspend.sh: 10: dbussuspend.sh: [[: not found 
Please enter either [now] or [#s|m|h|d] 

但是,應該閱讀,我已經進入了字符串5s運行elif下的代碼塊。我實際上已經嘗試使用任何正則表達式代替[0-9]*[smhd],所有錯誤都是一樣的。

+1

旁註:你可能需要'[0-9] + [smhd]'否則'h'將是一個可接受的輸入。 – Laurel

+0

你不需要'expr';您可以在原始正則表達式中使用捕獲組,然後訪問數組「BASH_REMATCH」中的捕獲值。 – chepner

回答

6

這個問題是不是由你的腳本,但你如何調用它:

sh dbussuspend.sh 

應該是:

bash dbussuspend.sh 

bash知道如何[[,但sh不...

更好,請按照Gordon Davisson的建議。做一次:

chmod +x dbussuspend.sh 

和此後,調用是這樣的:

./dbussuspend.sh 

另外,Etan Reisnerchepner問題您使用的expr,並laurelbash正則表達式。 GNU coreutils sleep支持例如sleep 30ssleep 2msleep 1h。用man sleep在您的系統上檢查此項。如果是這樣,那麼這將工作:

elif [[ "$sustime" =~ ^[0-9]+[smhd]$ ]] 
then 
    sudo sleep $sustime ; sudo pm-suspend 

^$^[0-9]+[smhd]$相匹配的開始和結束的字符串,並防止匹配,例如「uzeifue 1S ziufzr」。)

+0

也不要使用'expr'。特別是當你看起來像是在分割輸入,然後再立即把它們放回去。 –

+1

甚至比明確使用'bash'更好,你應該使用'chmod + x dbussuspend.sh'使腳本可執行(如果它不是),那麼使用'。/ dbussuspend.sh'運行它, shebang行(它已經是'/ bin/bash'了,應該是這樣)。 –

+1

Omg我喜歡這個網站。非常感謝每個人,真的爲我清除它。 – chepurko