I know that in various programming languages there is an option to hold two or more variables (or just one variable) by some variable; a typical example in general is to store coordinates.

Is this practice of holding two or more variables by one variable exist in shell (say, Bash) and what would be a typical example?

  • Check arrays in bash gnu.org/software/bash/manual/html_node/Arrays.html Aug 6 '21 at 3:44
  • I don't mean to mere arrays holding values (which aren't variables), did you mean to say that arrays in Bash can also include variables inside the array? Aug 6 '21 at 3:57
  • You can use so name associate arrays: linuxhint.com/associative_array_bash Aug 6 '21 at 4:49
  • 1
    Keep in mind that in the shell, variables are untyped, i.e. (apart from arrays) they are all just strings. Structured types such as a struct or object in C++ don't exist in the shell, if that is what you are referring to.
    – AdminBee
    Aug 6 '21 at 7:24
  • 1
    If the number of accesses to the variables is rare, I'm happy to store them as strings like Position="$x,$y" and split them as IFS=, read -r x y <<<"${Position}"`. But I would usually take this as a hint that awk or perl might be a better solution. Aug 6 '21 at 8:34

In order to get the values out you typically give the values names. For a coordinate example you might use x and y, and then have some syntax like point.x to get to it.

Bash has associative arrays, which are like maps or hash tables in other languages. You can use them as

declare -A point
echo "${point[x]}"

The syntax is ugly, but feature like this need to be added in a (mostly) backward compatible way. The Bourne shell has been around since 1979 (currently 42 years) and it is hard to find new constructs which don't already mean something.

  • 1
    You can also create (fake) a two-dimensional associative array with "variable" names, by assigning indexes like D2[hook,x]=45; D2[line,y]=88; Aug 6 '21 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.