Bash 如何将范围保存到变量,以便稍后在for循环中使用
我想在变量中保存一个范围,以便稍后在for循环中使用它 我有密码:Bash 如何将范围保存到变量,以便稍后在for循环中使用,bash,shell,for-loop,range,Bash,Shell,For Loop,Range,我想在变量中保存一个范围,以便稍后在for循环中使用它 我有密码: handshake=("wink" "double blink" "close your eyes" "jump") code=$1 result=() if ((code >> 4)); then for i in {3..0..-1}; do ((1 & (code >> i))) &&
handshake=("wink" "double blink" "close your eyes" "jump")
code=$1
result=()
if ((code >> 4)); then
for i in {3..0..-1}; do
((1 & (code >> i))) && result+=("${handshake[$i]}")
done
else
for i in {0..3}; do
((1 & (code >> i))) && result+=("${handshake[$i]}")
done
fi
我想重新编写结构,如:
range=((code >> 4)) ? {3..0..-1} : {0..3}
for i in $range; do
((1 & (code >> i))) && result+=("${handshake[$i]}")
done
如何在bash中执行此操作?带有立即序列表达式的for循环按预期工作:
for abc in {0..3}; do echo $abc; done
包含序列表达式的$var for循环需要另一个扩展:
#!/bin/bash
if [ $# -eq 0 ]; then
echo missing arg
exit 1
else
code=$1
fi
# range=((code >> 4)) ? {3..0..-1} : {0..3}
[[ $((code >> 4)) != 0 ]] && range={3..0} || range={0..3}
echo range: \"$range\"
echo -e "\nloop:"
for abc in $(eval echo $range); do
echo -n "$abc "
done
echo
还有更多的讨论我找到了一个可能的解决方案
#!/usr/bin/env bash
readonly handshake=("wink" "double blink" "close your eyes" "jump")
readonly code=$1
((code >> 4)) && range=({3..0}) || range=({0..3})
for i in "${range[@]}"; do
if ((1 & (code >> i))); then
[[ -n $result ]] && result+=","
result+="${handshake[$i]}"
fi
done
echo "$result"
很好的改进