Home > Net >  how to append one element to a GNU bash array variable and use that array variable as arguments to a
how to append one element to a GNU bash array variable and use that array variable as arguments to a

Time:09-21

In the Bismon static source code analyzer (GPLv3 licensed, git commit 49dd1bd232854a) for embedded C and C code (using a plugin for GCC 10 straight compiler on Debian bookworm for x86-64) I have a test Bash script Hello-World-Analyze which uses a GNU array variable bismon_hello_args.

That variable is declared (at line 56) using:

declare -a bismon_hello_args

and I would like to fill that bismon_hello_args array variable from script arguments starting with --bismon, and later invoke the bismon executable (compiled from C source files) with several arguments to its main being the elements of that bismon_hello_args array variable.

So if my Hello-World-Analyze script is invoked as Hello-World-Analyze --bismon-debug-after-load --bismon-anon-web-cookie=/tmp/bismoncookie --gcc=/usr/local/bin/gcc-11 I want the bismon ELF executable to be started with two arguments (so argc=3, in C parlance) : --bismon-debug-after-load followed by --bismon-anon-web-cookie=/tmp/bismoncookie

For some reason, the following code (lines 58 to 64) in that Hello-World-Analyze script:

for f in "$@"; do
    case "$f" in
    --bismon*) bismon_hello_args =$f;;
    --asm) export BISMON_PLUGIN_ASMOUT=/tmp/gcc10_metaplugin_BMGCC.s;;
    --gcc=*) export BISMON_GCC=$(echo $f | /bin/sed -e s/--gcc=//);;
    esac
done

does not work as expected. It should be (and was in a previous git commit e8c3d795bc9dc8) later followed with

./bismon $bismon_hello_args &

But debugging prints show that bismon is invoked with argc=2 so one long argv[1] program argument...

What am I doing wrong?

CodePudding user response:

Merely = adds a string to an existing string. You probably want bismon_hello_args =("$f");; (notice also the quotes). To call the program, use ./bismon "${bismon_hello_args[@]}" & (notice the quotes, again).

The syntax to use an array variable is different than the syntax for simple scalars. This syntax was inherited from ksh, which in turn needed to find a way to introduce new behavior without sacrificing compatibility with existing Bourne shell scripts.

Without the array modifiers, Bash simply accesses the first element of the array. (This confuses beginners and experienced practitioners alike.)

  • Related