for能够使用数组来定义变量么吗?

sh/bash/dash/ksh/zsh等Shell脚本
回复
yubinalice
帖子: 197
注册时间: 2015-12-23 16:20
系统: ubuntu 16.04

for能够使用数组来定义变量么吗?

#1

帖子 yubinalice » 2017-07-17 20:56

如题,

刚刚写了一个脚本,

我自己没有找到任何的问题,

但是机器就是不按照预定的方式运行。

for i in [1,100]
do
echo $i
done

预定的结果是从1到100,

但是返回的其实是

[1,100]

这个令我很奇怪。

谁知道这个是怎么回事?

目前这个脚本已被我改装成

for ((i=1;i<=100;i++))
do
echo $i
done

并且运行完美。
头像
astolia
论坛版主
帖子: 6396
注册时间: 2008-09-18 13:11

Re: for能够使用数组来定义变量么吗?

#2

帖子 astolia » 2017-07-17 21:53

yubinalice 写了:如题,

刚刚写了一个脚本,

我自己没有找到任何的问题,

但是机器就是不按照预定的方式运行。

for i in [1,100]
do
echo $i
done

预定的结果是从1到100,

但是返回的其实是

[1,100]

这个令我很奇怪。
我也觉得很奇怪,你连基本的shell语法都不会,想当然瞎写,还觉得没有任何问题,你哪里来的自信?
看懂了下面的你就知道为什么会返回[1,100]

代码: 全选

       for name [ [ in [ word ... ] ] ; ] do list ; done
              The list of words following in is expanded, generating a list of items.  The variable name is set to each element of this
              list  in  turn,  and  list is executed each time.  If the in word is omitted, the for command executes list once for each
              positional parameter that is set (see PARAMETERS below).  The return status is the exit status of the last  command  that
              executes.   If the expansion of the items following in results in an empty list, no commands are executed, and the return
              status is 0.
看懂了下面的你就知道正确的写法是什么

代码: 全选

       A sequence expression takes the form {x..y[..incr]}, where x and y are either  integers  or  single  characters,  and  incr,  an
       optional  increment,  is  an integer.  When integers are supplied, the expression expands to each number between x and y, inclu‐
       sive.  Supplied integers may be prefixed with 0 to force each term to have the same width.  When either x or  y  begins  with  a
       zero,  the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary.  When
       characters are supplied, the expression expands to each character lexicographically  between  x  and  y,  inclusive,  using  the
       default  C  locale.  Note that both x and y must be of the same type.  When the increment is supplied, it is used as the differ‐
       ence between each term.  The default increment is 1 or -1 as appropriate.
回复