无法在bash中向数组添加元素 [英] Unable to add element to array in bash

查看:50
本文介绍了无法在bash中向数组添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.让我们假设 $@ 只包含有效文件.变量 file 包含当前文件的名称(我当前打开"的文件).然后变量 element 包含格式 file:function.

I have the following problem. Let´s assume that $@ contains only valid files. Variable file contains the name of the current file (the file I'm currently "on"). Then variable element contains data in the format file:function.

现在,当变量元素不为空时,应该将其放入数组中.这就是问题所在.如果我回显 element,它包含我想要的内容,尽管它没有存储在数组中,因此 for cycle 不会打印出任何内容.

Now, when variable element is not empty, it should be put into the array. And that's the problem. If I echo element, it contains exactly what I want, although it is not stored in array, so for cycle doesn't print out anything.

我写了两种尝试将元素插入数组的方法,但都不起作用.你能告诉我,我做错了什么吗?

I have written two ways I try to insert element into array, but neither works. Can you tell me, What am I doing wrong, please?

我使用的是 Linux Mint 16.

I'm using Linux Mint 16.

#!/bin/bash

nm $@ | while read line
do
  pattern="`echo \"$line\" | sed -n \"s/^\(.*\):$/\1/p\"`"
  if [ -n "$pattern" ]; then
    file="$pattern"  
  fi
  element="`echo \"$line\" | sed -n \"s/^U \([0-9a-zA-Z_]*\).*/$file:\1/p\"`"
  if [ -n "$element" ]; then
    array+=("$element")
    #array[$[${#array[@]}+1]]="$element"
    echo element - "$element"
  fi
done

for j in "${array[@]}"
do
  echo "$j"
done

推荐答案

您的问题是 while 循环在子 shell 中运行,因为它是管道中的第二个命令,因此在循环退出后该循环不可用.

Your problem is that the while loop runs in a subshell because it is the second command in a pipeline, so any changes made in that loop are not available after the loop exits.

您有几个选择.我经常将 {} 用于 命令分组:

You have a few options. I often use { and } for command grouping:

nm "$@" |
{
while read line
do
    …
done
for j in "${array[@]}"
do
    echo "$j"
done
}

bash 中,您还可以使用 进程替换:

In bash, you can also use process substitution:

while read line
do
    …
done < <(nm "$@")

<小时>

此外,最好使用 $(...) 代替反引号 `...`(这不仅仅是因为将引号反引号很困难)降价文字!).


Also, it is better to use $(…) in place of back-quotes `…` (and not just because it is hard work getting back quotes into markdown text!).

您的线路:

element="`echo \"$line\" | sed -n \"s/^U \([0-9a-zA-Z_]*\).*/$file:\1/p\"`"

可以写成:

element="$(echo "$line" | sed -n "s/^U \([0-9a-zA-Z_]*\).*/$file:\1/p")"

甚至:

element=$(echo "$line" | sed -n "s/^U \([0-9a-zA-Z_]*\).*/$file:\1/p")

当您需要嵌套它们时,它真的很有帮助.例如,要列出与 gcc 所在位置相邻的 lib 目录:

It really helps when you need them nested. For example, to list the lib directory adjacent to where gcc is found:

ls -l $(dirname $(dirname $(which gcc)))/lib

对比

ls -l `dirname \`dirname \\\`which gcc\\\`\``/lib

我知道哪个更容易!

这篇关于无法在bash中向数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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