我有一些可能的(字符串)值: a b c
。 我希望a循环地在这些值之间切换:
if [ "$value" == "a" ]; then value=b
elif [ "$value" == "b"]; then value=c
elif [ "$value" == "c"]; then value=a
fi
使用这种方法,有没有更加高效的方式来实现,以便我可以支持许多选项,比如a b c ... z
?
我有一些可能的(字符串)值: a b c
。 我希望a循环地在这些值之间切换:
if [ "$value" == "a" ]; then value=b
elif [ "$value" == "b"]; then value=c
elif [ "$value" == "c"]; then value=a
fi
使用这种方法,有没有更加高效的方式来实现,以便我可以支持许多选项,比如a b c ... z
?
It can be done like this:
get_next()
{
__current_i=${__current_i:- 0} # global variable that saves index of current value
[ $__current_i -ge $# ] && __current_i=0 # if we exceed the number of values, then reset to zero
shift $__current_i # move to current value
((__current_i++)) # increment index
echo $1
}
val="a b c d"
get_next $val
get_next $val
get_next $val
get_next $val
get_next $val
你可以使用Bash数组
vals=('a' 'b' 'c')
value=$1
max=$(( ${#vals[@]} - 1 ))
count=0
while [ "$value" != "${vals[count]}" ]
do
count=$(( $count + 1 ))
done
if [ $count -eq $max ]; then
count=0
else
count=$(( $count + 1 ))
fi
echo ${vals[count]}
为什么这么复杂?
这会做你想要的:
while true; do
for x in a b c; do
echo "$x"
done
done
a->b
和b->a
形成了一个循环,会怎么样? - luoluo