# Tricky implementation of two-dimensional array in Bash.

arr[i*100+j]="whatever"
Since Bash doesn't support two-dimensional arrays, you can limit your columns length by some big enough constant value ( in this example 100 ) and then index the array with i and j, or maybe write your own get() and set() methods to index the array properly like I implemented for example ( see Sample output ). For example for i=0 and j=0...99 you'll pick up one of 100 elements in the range [0,99] in the one-dimensional array. For i=1 and j=0...99 you'll pick up one of 100 elements in the range [100,199]. And so on. Be careful when using this, and remember that in fact you are always using one-dimensional array.
Sample Output
```rany:~\$ # READ DESCRIPTION FIRST.
rany:~\$ set() { i="\$1";j="\$2";val="\$3";arr[\$((i*100+j))]="\$val"; }
rany:~\$ set 0 0 "hello"
rany:~\$ set 0 1 "world"
rany:~\$ set 0 99 "how"
rany:~\$ set 1 0 "are"
rany:~\$ set 1 99 "you?"
rany:~\$ echo "\${arr[0]} \${arr[1]} \${arr[99]} \${arr[100]} \${arr[199]}"
hello world how are you?
rany:~\$ get() { i="\$1";j="\$2"; echo "\${arr[\$((i*100+j))]}"; }
rany:~\$ get 0 99
how
rany:~\$ get 1 0
are
rany:~\$ get 1 99
you?
rany:~\$```

9
2011-02-18 00:47:25

## 1 Alternatives + Submit Alt

• -1
getarray(){ a=\$1;b="\${a[\$2]}";eval "c=\$b";echo "\${c[\$3]}";return 0;};a[0]="( a b c )";a[1]="( d e f )";getarray a 1 2
· 2011-02-20 00:58:41

### What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

### What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.