在一个循环中赋值给变量 [英] assign a value to a variable in a loop

查看:386
本文介绍了在一个循环中赋值给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有2件code在这里,和 $ 1 中的值是一个包含3行文本文件的名称。

现在,我有一个问题。在第一块code,我不能得到正确的价值圈外,但在第二片code,我能得到正确的结果。我不知道为什么。

我怎样才能让code的第一件得到正确的结果呢?

 #!/斌/庆典数= 0
猫$ 1|而读线

    数= $ [$计数+ 1]
DONE
回声中的所有$计数线(S)。#-----------------------------------------COUNT2 = 0
在A B C无功

    COUNT2 = $ [$ COUNT2 + 1]
DONE
回声$ COUNT2线(S)的所有。


解决方案

这是因为while循环前的管道。它创建一个子shell,因而在变量的变化不会传递到主脚本。为了克服这个问题,使用进程替换来代替:

 同时读取-r线

    #做一些东西
完成< ≤(一些commad)

在4.2版或更高版本,您还可以设置 lastpipe 选项,最后一个命令
在该管道将在当前shell中运行,而不是一个子shell。

 禁用了javascript -s lastpipe
一些命令|而读-r线;做
  #做一些东西
DONE

在此情况下,因为你只是用文件的内容,你可以使用输入重定向:

 同时读取-r线

    #做一些东西
完成< $文件

There are 2 pieces of code here, and the value in $1 is the name of a file which contains 3 lines of text.

Now, I have a problem. In the first piece of the code, I can't get the "right" value out of the loop, but in the second piece of the code, I can get the right result. I don't know why.

How can I make the first piece of the code get the right result?

#!/bin/bash

count=0
cat "$1" | while read line
do
    count=$[ $count + 1 ]
done
echo "$count line(s) in all."

#-----------------------------------------

count2=0
for var in a b c
do
    count2=$[ $count2 + 1 ]
done
echo "$count2 line(s) in all."

解决方案

This happens because of the pipe before the while loop. It creates a sub-shell, and thus the changes in the variables are not passed to the main script. To overcome this, use process substitution instead:

while read -r line
do
    # do some stuff
done < <( some commad)

In version 4.2 or later, you can also set the lastpipe option, and the last command in the pipeline will run in the current shell, not a subshell.

shopt -s lastpipe
some command | while read -r line; do
  # do some stuff
done

In this case, since you are just using the contents of the file, you can use input redirection:

while read -r line
do
    # do some stuff
done < "$file"

这篇关于在一个循环中赋值给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆