LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 968|回复: 8

如何在环境变量里边一次读取2个变量?

[复制链接]
发表于 2006-8-18 14:42:32 | 显示全部楼层 |阅读模式
这样一个环境变量:
$a = "1 a 2 b 3 c"

我想在用for/while循环里边,一次读取2个值,放入2个变量中。怎么弄?

比如第1次循环, $x = 1, $y = a
  第2次循环, $x = 2, $y = b
这样

read 似乎不能从 环境变量 中读取内容,郁闷了。

哪位帮一下。。谢谢。
发表于 2006-8-18 15:26:04 | 显示全部楼层
put "\n" on each two of them should work
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-8-18 15:31:08 | 显示全部楼层
谢谢,,还是用perl解决算了。。。:)。。
回复 支持 反对

使用道具 举报

发表于 2006-8-18 15:40:37 | 显示全部楼层
or maybe this code can work well
  1. count=0
  2. for item in $a;
  3. do
  4.         let 'count=count+1'
  5.         if [ $count -eq 1 ];then
  6.                 x=$item
  7.                 count=0
  8.                 echo $x
  9.         else
  10.                 y=$item
  11.                 echo $y
  12.         fi
  13. done
复制代码
回复 支持 反对

使用道具 举报

发表于 2006-8-19 00:51:40 | 显示全部楼层
Post by Iambitious
or maybe this code can work well
  1. count=0
  2. for item in $a;
  3. do
  4.         let 'count=count+1'
  5.         if [ $count -eq 1 ];then
  6.                 x=$item
  7.                 count=0
  8.                 echo $x
  9.         else
  10.                 y=$item
  11.                 echo $y
  12.         fi
  13. done
复制代码
I doubt. First of all, loop still bases on step 1. you are not reading 2 at a time. Second, I do not think you can have y assigned even though you set count to 0 but that if test has been done.
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-8-19 01:30:32 | 显示全部楼层
谢谢大家的好意,还是用perl算了。能解决问题就好。
回复 支持 反对

使用道具 举报

发表于 2006-8-19 11:47:52 | 显示全部楼层
yeah you are right.
the code still run step by step, but in truth it can take the same effect.
there are some bugs in my code because I did not test it well. That's my fault.
the rivision is below:
  1. count=1
  2. for item in $a;
  3. do
  4.         let 'count=count+1'
  5.         if [ $count -eq 2 ];then
  6.                 x=$item
  7.                 count=0
  8.                 echo "x:$x"
  9.         else
  10.                 y=$item
  11.                 echo "y:$y"
  12.         fi
  13. done
复制代码
here is the results:
x:1
y:a
x:2
y:b
x:3
y:c
x:4
y:d
回复 支持 反对

使用道具 举报

发表于 2006-8-19 15:07:05 | 显示全部楼层
a=(1 a 2 b 3 c)
x=1
y=2
while [[ -n $a[$x] ]]; do
echo $a[$x] $a[$y]
x=$((x+2))
y=$((y+2))
done
回复 支持 反对

使用道具 举报

发表于 2006-8-23 10:39:55 | 显示全部楼层
Post by seamonkey
a=(1 a 2 b 3 c)
x=1
y=2
while [[ -n $a[$x] ]]; do
echo $a[$x] $a[$y]
x=$((x+2))
y=$((y+2))
done
楼上的程序有几个小毛病:
a=(1 a 2 b 3 c)
x=0
y=1
while [[ -n ${a[$x]} ]]; do
echo ${a[$x]} ${a[$y]}
x=$((x+2))
y=$((y+2))
done
这样就可以了。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表