2015-06-15 39 views
2

我正在寫一個bash腳本,我想驗證一個字符串是否是一個shell保留字(如ifforalias等)。如何測試命令是否爲shell保留字?

我該如何做到這一點?

+2

對正式名單檢查? http://www.gnu.org/software/bash/manual/html_node/Reserved-Word-Index.html –

回答

6
#!/bin/bash 

string="$1" 

if [[ $(type "$string" 2>&1) == "$string is a shell"* ]]; then 
    echo "Keyword $string is reserved by shell" 
fi 
+0

我只是爲了個人的完全右手比賽。它不可能傷害並使事情更清楚。可能甚至與'$ string'完全匹配。 –

+2

@Etan Reisner:問題是:'type echo' =>'echo是一個shell內建函數',而'if if' =>'if是一個shell關鍵字'。 –

+0

@EtanReisner如果顯示在該目錄中,將顯示什麼內容? – 123

1

如果你只想要Shell關鍵字,則:

#!/bin/bash 
string="$1" 
[[ $(type -t "$string" 2>&1) == "keyword" ]] && echo reserved || echo not reserved 

內建不會通過這項測試(僅適用於關鍵字)。

與在各種情況下延伸的可能性這樣做的一種方式:

#!/bin/bash 
string="$1" 
checkfor=('keyword' 'builtin') 
for ((i=0;i<${#checkfor[@]};i++)) 
do 
    [[ $(type -t "$string" 2>&1) == "${checkfor[$i]}" ]] && reserved=true && break || reserved=false 
done 
[[ $reserved == true ]] && echo reserved || echo not reserved 

commandhashaliastype等。(內建)將通過上述試驗以及關鍵字。

您可以通過添加元素到數組checkfor添加其他可能的測試條件:

checkfor=('keyword' 'builtin' 'file' etc...)