[英]BASH: Best way to set variable from array
Bash 4 on Linux ~ Bash 4 上 Linux ~
I have an array of possible values.我有一组可能的值。 I must restrict user input to these values.
我必须将用户输入限制为这些值。
Arr=(hello kitty goodbye quick fox)
User supplies value as argument to script:用户提供值作为脚本的参数:
bash myscript.sh -b var
Currently, I'm trying the following:目前,我正在尝试以下方法:
function func_exists () {
_var="$1"
for i in ${Arr[@]}
do
if [ "$i" == "$_var" ]
then
echo hooray for "$_var"
return 1
fi
done
return 0
}
func_exists $var
if [ $? -ne 1 ];then
echo "Not a permitted value."
func_help
exit $E_OPTERROR
fi
Seems to work fine, are there better methods for testing user input against an array of allowed values?似乎工作正常,是否有更好的方法来针对一组允许值测试用户输入?
UPDATE: I like John K's answer...can someone clarify the use of $@?更新:我喜欢约翰 K 的回答......有人可以澄清 $@ 的使用吗? I understand that this represents all positional parameters -- so we shift the first param off the stack and $@ now represents all remaining params, those being the passed array...is that correct?
我知道这代表所有位置参数——所以我们将第一个参数移出堆栈,$@ 现在代表所有剩余的参数,那些是传递的数组......对吗? I hate blindly using code without understanding...even if it works!
我讨厌盲目地使用代码而不理解......即使它有效!
function func_exists () {
case "$1"
in
hello)
kitty)
goodbye)
quick)
fox)
return 1;;
*)
return 0;;
esac
}
Your solution is what I'd do.你的解决方案就是我会做的。 Maybe using a few more shell-isms, such as returning 0 for success and non-0 for failure like UNIX commands do in general.
也许使用更多的 shell-isms,例如返回 0 表示成功,返回非 0 表示失败,如 UNIX 命令一般。
# Tests if $1 is in the array ($2 $3 $4 ...).
is_in() {
value=$1
shift
for i in "$@"; do
[[ $i == $value ]] && return 0
done
return 1
}
if ! is_in "$var" "${Arr[@]}"; then
echo "Not a permitted value." >&2
func_help
exit $E_OPTERROR
fi
Careful use of double quotes makes sure this will work even if the individual array entries contain spaces, which is allowed.仔细使用双引号可确保即使单个数组条目包含空格,这也能正常工作,这是允许的。 This is a two element array:
list=('hello world' 'foo bar')
.这是一个两元素数组:
list=('hello world' 'foo bar')
。
Another solution.另一种解决方案。 is_in is just a variable:
is_in 只是一个变量:
Arr=(hello kitty goodbye quick fox)
var='quick'
string=" ${Arr[*]} " # array to string, framed with blanks
is_in=1 # false
# try to delete the variable inside the string; true if length differ
[ "$string" != "${string/ ${var} /}" ] && is_in=0
echo -e "$is_in"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.