Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何将范围保存到变量,以便稍后在for循环中使用_Bash_Shell_For Loop_Range - Fatal编程技术网

Bash 如何将范围保存到变量,以便稍后在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))) &&

我想在变量中保存一个范围,以便稍后在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))) && 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"

很好的改进