在bash设置',而读“循环变量后,未设置 [英] Variables set in a bash 'while read' loop are unset after it

查看:101
本文介绍了在bash设置',而读“循环变量后,未设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以下code将命令的输出存储在一个阵列
但数组元素不能在while循环之后被打印
我的意思是在我的code的最后一行
是否有任何问题,我的code?

 #! /斌/庆典LS -a |而读线做
    数组[$ i] =$行        回声$ {数组[$ i]}
        ((我+ +))
DONE回声$ {数组[@]}< ------------


解决方案

现在的问题是,你在的的外壳添加元素。为了详细说明:

 命令1 |命令2

原因命令2 在一个子shell,这是一个独立的执行环境中执行。这意味着,在命令2 设置的变量是不提供给的电流的外壳,其执行环境不受影响。你也可以使用进程替换来实现相同的:

 而读线;做
 ...
完成< ≤(ls -l命令)

请注意,解析 LS 是不推荐的;尝试使用找到代替。

I try the code below to store the command output in an array but the array elements cannot be printed after the "while loop" I mean in the last line of my code is there any problem in my code?

#! /bin/bash

ls -a | while read line

do
    array[$i]="$line "  

        echo ${array[ $i ]}
        ((i++))
done

echo ${array[@]}  <------------

解决方案

The problem is that you add the elements in a subshell. To elaborate:

command1 | command2

causes command2 to be executed in a subshell, which is a separate execution environment. This implies that the variables set in command2 are not available to the current shell, whose execution environment is not affected. You could instead use process substitution to achieve the same:

while read line; do
 ...
done < <(ls -l)

Please note that parsing ls is not recommended; try using find instead.

这篇关于在bash设置',而读“循环变量后,未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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