1

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?

7
  • Check arrays in bash gnu.org/software/bash/manual/html_node/Arrays.html Commented Aug 6, 2021 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? Commented Aug 6, 2021 at 3:57
  • You can use so name associate arrays: linuxhint.com/associative_array_bash Commented Aug 6, 2021 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. Commented Aug 6, 2021 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. Commented Aug 6, 2021 at 8:34

1 Answer 1

2

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
point[x]=3
point[y]=4
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
  • 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; Commented Aug 6, 2021 at 11:02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.