Unable to add element to array in bash

后端 未结 1 1694
借酒劲吻你
借酒劲吻你 2020-12-16 22:34

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 cu

相关标签:
1条回答
  • 2020-12-16 23:23

    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
    }
    

    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!).

    Your line:

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

    could be written:

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

    or even:

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

    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
    

    vs

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

    I know which I find easier!

    0 讨论(0)
提交回复
热议问题