变量为“for循环”

时间:2017-02-03 04:42:43

标签: bash variables for-loop

我有两个变量,我正在尝试从其中一个变量运行for循环:

@cuda.jit

当我这样做时,我得到了:

a=5  
z="i=0;i<=$a;i++"
x="i=$a;i>=1;i--"
read -p "choose loop:" loop
  case "$loop" in
    plus ) l="$z" ;;
    minus ) l="$x" ;;
  esac

for (($l)) do
#also tried (('$l')) & (("$l"))
  ...
done

所以我试过了:

syntax error: arithmetic expression requiered
syntax error:'(($l))'

但是当我这样做时,我得到了:

a=5 x="\(\(i=1;i<=$a;i++\)\)" #also tried "((...))" for $x do ... done #also tried "$x" & '$x'

但我只想要一个“循环结构”我不想复制我的代码两次 那么我应该怎么做才能运行我的循环而不必在循环中编写我的代码两次?

3 个答案:

答案 0 :(得分:3)

您可以使用seq

将列表存储在变量中
loop_max=5
read -p "choose loop:" loop
case "$loop" in
  plus) myseq=$(seq 0 "$loop_max");;
  minus) myseq=$(seq "$loop_max" -1 0);;
esac

for i in $myseq; do
  echo "$i"
done

修改

您还可以在seq语句中设置case参数,并在seq循环中调用for

loop_max=5
read -p "choose loop:" loop
case "$loop" in
  plus) start="0";;
  minus) end="-1 0";;
esac

for i in $(seq $start "$loop_max" $end); do
  echo "$i"
done

答案 1 :(得分:2)

我认为int?语法不允许你尝试做什么。相反,这样做是为了让它更具可读性:

for

loop_max=5 read -p "choose loop:" loop case "$loop" in plus) loop_type="ascending" ;; minus) loop_type="descending" ;; esac [[ $loop_type == "ascending" ]] && for ((i = 0; i <= $loop_max; i++)); do : your code goes here done [[ $loop_type == "descending" ]] && for ((i = $loop_max; i > 0; i--)); do : your code goes here done 语句没有增加太多价值。所以,你可以这样重写整个事情:

case

答案 2 :(得分:0)

您可以修改for循环,如下所示:

loop_max=5
read -p "choose loop:" loop_type
if [[ $loop_type == "plus" ]]; then
  for ((i = 0; i <= $loop_max; i++)); do
    : your code goes here
  done
elif [[ $loop_type == "minus" ]]; then
  for ((i = $loop_max; i > 0; i--)); do
    : your code goes here
  done
else
  printf "Invalid choice.\n"
fi

希望这能解决你的目的。