0

Recently I learned there in bash is possible to pre-set variable. For example:

q=2 ./ecq

And I get 2 to output with

#!/bin/bash
# This file is ./ecq
echo "$q"

But with array I got error:

mn=( 1 2 3 ) ./pre

With ./pre:

#!/bin/bash
echo "${mn[0]}"

I get (1 2 3). How can I take mn pre-set array?

1 Answers1

1

There is no concept of a pre-set variable, whatever this would be.

The basic syntax of invoking an external command as a child process looks something like

a=x b=y c=z p u v w

I ignored here redirection operators, to keep things simple. This line basically starts a child process with the command p and passes to it the argumenst u, v and w. Every new process needs an environment, which is basically a mapping from names (the so-called environment variables) to some strings. The environment for the process p is a copy of the environment from the calling process (i.e. your shell script), but enhanced by setting the environment variable a to x, the variable b to y and c to z.

Now you want to set an environment variable having an array as value. This does not work. The value of an environment variable must be a string, because invoking child processes is a general concept (not bound to a certain programming language like bash), and every programming language has some way to deal with a string and is supposed to offer a library function to access the environment (For instance the function getenv when you are doing C programming). We don't even know whether the programming language used to implement your process p does have arrays. Imagine that p is written as POSIX shell scripts - you don't have arrays like you do in bash or zsh, when you are doing POSIX shell.

user1934428
  • 19,864
  • 7
  • 42
  • 87