I am writing a bash script and I would like to verify if a string is a shell reserved word (like if
, for
, alias
, etc...).
How can I can do this?
答案 0 :(得分:6)
#!/bin/bash
string="$1"
if [[ $(type "$string" 2>&1) == "$string is a shell"* ]]; then
echo "Keyword $string is reserved by shell"
fi
答案 1 :(得分:1)
If you want only the shell keywords, then:
#!/bin/bash
string="$1"
[[ $(type -t "$string" 2>&1) == "keyword" ]] && echo reserved || echo not reserved
builtins won't pass this test (only keywords).
A way of doing this with possibility of extending in various cases:
#!/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
command
, hash
, alias
, type
etc.. (builtins) will pass the above test as well as keywords.
You can add other possible test conditions by adding an element into the array checkfor
:
checkfor=('keyword' 'builtin' 'file' etc...)