Associative Arrays in Shell Scripts
I saw a trick for implementing associative arrays in a shell script. For example print array["apples"]
could be scripted as echo $array$key
where key=apples.
However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.
So, is there some other way to store the keys for later use?
shell-script associative-array
add a comment |
I saw a trick for implementing associative arrays in a shell script. For example print array["apples"]
could be scripted as echo $array$key
where key=apples.
However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.
So, is there some other way to store the keys for later use?
shell-script associative-array
5
If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)
– Martin von Wittich
Jan 29 '14 at 0:09
@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect
– Slav
Nov 19 '14 at 14:16
2
@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.
– Martin von Wittich
Nov 19 '14 at 22:50
add a comment |
I saw a trick for implementing associative arrays in a shell script. For example print array["apples"]
could be scripted as echo $array$key
where key=apples.
However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.
So, is there some other way to store the keys for later use?
shell-script associative-array
I saw a trick for implementing associative arrays in a shell script. For example print array["apples"]
could be scripted as echo $array$key
where key=apples.
However, there was no mention of how to generate the keys to iterate over the array.
The only way I could think of was to store the keys in a variable delimited by spaces so I could use a for-loop to iterate over the array.
So, is there some other way to store the keys for later use?
shell-script associative-array
shell-script associative-array
edited Feb 2 '16 at 13:05
dkb
1296
1296
asked Jan 28 '14 at 22:35
EggHeadEggHead
175128
175128
5
If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)
– Martin von Wittich
Jan 29 '14 at 0:09
@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect
– Slav
Nov 19 '14 at 14:16
2
@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.
– Martin von Wittich
Nov 19 '14 at 22:50
add a comment |
5
If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)
– Martin von Wittich
Jan 29 '14 at 0:09
@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect
– Slav
Nov 19 '14 at 14:16
2
@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.
– Martin von Wittich
Nov 19 '14 at 22:50
5
5
If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)
– Martin von Wittich
Jan 29 '14 at 0:09
If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)
– Martin von Wittich
Jan 29 '14 at 0:09
@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect
– Slav
Nov 19 '14 at 14:16
@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect
– Slav
Nov 19 '14 at 14:16
2
2
@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.
– Martin von Wittich
Nov 19 '14 at 22:50
@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.
– Martin von Wittich
Nov 19 '14 at 22:50
add a comment |
4 Answers
4
active
oldest
votes
Shells with associative arrays
Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a
is an associative array, then "${!a[@]}"
is the array of its keys:
for k in "${!a[@]}"; do
echo "$k -> ${a[$k]}"
done
In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:
for k in "${(@k)a}"; do
echo "$k -> $a[$k]"
done
${(k)a}
also works if a
does not have an empty key.
In zsh, you could also loop on both k
eys and v
alues at the same time:
for k v ("${(@kv)a}") echo "$k -> $v"
Shells without associative arrays
Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.
If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z
(ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.
## ainit STEM
## Declare an empty associative array named STEM.
ainit () {
eval "__aa__${1}=' '"
}
## akeys STEM
## List the keys in the associatve array named STEM.
akeys () {
eval "echo "$__aa__${1}""
}
## aget STEM KEY VAR
## Set VAR to the value of KEY in the associative array named STEM.
## If KEY is not present, unset VAR.
aget () {
eval "unset $3
case $__aa__${1} in
*" $2 "*) $3=$__aa__${1}__$2;;
esac"
}
## aset STEM KEY VALUE
## Set KEY to VALUE in the associative array named STEM.
aset () {
eval "__aa__${1}__${2}=$3
case $__aa__${1} in
*" $2 "*) :;;
*) __aa__${1}="${__aa__${1}}$2 ";;
esac"
}
## aunset STEM KEY
## Remove KEY from the associative array named STEM.
aunset () {
eval "unset __aa__${1}__${2}
case $__aa__${1} in
*" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
esac"
}
(Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)
add a comment |
I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]}
syntax:
$ typeset -A foo=([key1]=bar [key2]=baz);
$ echo "${!foo[@]}"
key2 key1
So, to iterate:
$ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
key2 : baz
key1 : bar
I found a nice, short tutorial on this here.
As pointed out in the comments below, associative arrays were added in bash
version 4. See here for a Linux journal article on the subject.
1
(bash version 4 only)
That's an important thing to note. Traditionally,bash
arrays are numeric only.
– Ricky Beam
Jan 28 '14 at 23:07
1
You might want to usetypeset
instead ofdeclare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.
– jlliagre
Jan 29 '14 at 1:00
add a comment |
Shells without associative arrays
It's not that hard when keys are restricted to [0-9A-Za-z_]
(numbers, letters, underscore).
The trick is instead of storing to array[$key], store to variables array_$key.
Set:
eval "array_$key='$value'"
Get:
value=`eval echo '$'array_$key`
Note: Values cannot contain '
(single quote).
add a comment |
this works in bash
cert="first"
web="second"
declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
echo "first is" ${assoc_array[cert]}
echo "second is" ${assoc_array[web]}
OR
#loop
for i in "${assoc_array[@]}"
do
echo "$i"
done
No need to use eval afaik
New contributor
I believe that you've missed the point of the question.
– G-Man
4 hours ago
add a comment |
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "106"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f111397%2fassociative-arrays-in-shell-scripts%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
Shells with associative arrays
Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a
is an associative array, then "${!a[@]}"
is the array of its keys:
for k in "${!a[@]}"; do
echo "$k -> ${a[$k]}"
done
In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:
for k in "${(@k)a}"; do
echo "$k -> $a[$k]"
done
${(k)a}
also works if a
does not have an empty key.
In zsh, you could also loop on both k
eys and v
alues at the same time:
for k v ("${(@kv)a}") echo "$k -> $v"
Shells without associative arrays
Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.
If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z
(ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.
## ainit STEM
## Declare an empty associative array named STEM.
ainit () {
eval "__aa__${1}=' '"
}
## akeys STEM
## List the keys in the associatve array named STEM.
akeys () {
eval "echo "$__aa__${1}""
}
## aget STEM KEY VAR
## Set VAR to the value of KEY in the associative array named STEM.
## If KEY is not present, unset VAR.
aget () {
eval "unset $3
case $__aa__${1} in
*" $2 "*) $3=$__aa__${1}__$2;;
esac"
}
## aset STEM KEY VALUE
## Set KEY to VALUE in the associative array named STEM.
aset () {
eval "__aa__${1}__${2}=$3
case $__aa__${1} in
*" $2 "*) :;;
*) __aa__${1}="${__aa__${1}}$2 ";;
esac"
}
## aunset STEM KEY
## Remove KEY from the associative array named STEM.
aunset () {
eval "unset __aa__${1}__${2}
case $__aa__${1} in
*" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
esac"
}
(Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)
add a comment |
Shells with associative arrays
Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a
is an associative array, then "${!a[@]}"
is the array of its keys:
for k in "${!a[@]}"; do
echo "$k -> ${a[$k]}"
done
In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:
for k in "${(@k)a}"; do
echo "$k -> $a[$k]"
done
${(k)a}
also works if a
does not have an empty key.
In zsh, you could also loop on both k
eys and v
alues at the same time:
for k v ("${(@kv)a}") echo "$k -> $v"
Shells without associative arrays
Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.
If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z
(ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.
## ainit STEM
## Declare an empty associative array named STEM.
ainit () {
eval "__aa__${1}=' '"
}
## akeys STEM
## List the keys in the associatve array named STEM.
akeys () {
eval "echo "$__aa__${1}""
}
## aget STEM KEY VAR
## Set VAR to the value of KEY in the associative array named STEM.
## If KEY is not present, unset VAR.
aget () {
eval "unset $3
case $__aa__${1} in
*" $2 "*) $3=$__aa__${1}__$2;;
esac"
}
## aset STEM KEY VALUE
## Set KEY to VALUE in the associative array named STEM.
aset () {
eval "__aa__${1}__${2}=$3
case $__aa__${1} in
*" $2 "*) :;;
*) __aa__${1}="${__aa__${1}}$2 ";;
esac"
}
## aunset STEM KEY
## Remove KEY from the associative array named STEM.
aunset () {
eval "unset __aa__${1}__${2}
case $__aa__${1} in
*" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
esac"
}
(Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)
add a comment |
Shells with associative arrays
Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a
is an associative array, then "${!a[@]}"
is the array of its keys:
for k in "${!a[@]}"; do
echo "$k -> ${a[$k]}"
done
In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:
for k in "${(@k)a}"; do
echo "$k -> $a[$k]"
done
${(k)a}
also works if a
does not have an empty key.
In zsh, you could also loop on both k
eys and v
alues at the same time:
for k v ("${(@kv)a}") echo "$k -> $v"
Shells without associative arrays
Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.
If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z
(ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.
## ainit STEM
## Declare an empty associative array named STEM.
ainit () {
eval "__aa__${1}=' '"
}
## akeys STEM
## List the keys in the associatve array named STEM.
akeys () {
eval "echo "$__aa__${1}""
}
## aget STEM KEY VAR
## Set VAR to the value of KEY in the associative array named STEM.
## If KEY is not present, unset VAR.
aget () {
eval "unset $3
case $__aa__${1} in
*" $2 "*) $3=$__aa__${1}__$2;;
esac"
}
## aset STEM KEY VALUE
## Set KEY to VALUE in the associative array named STEM.
aset () {
eval "__aa__${1}__${2}=$3
case $__aa__${1} in
*" $2 "*) :;;
*) __aa__${1}="${__aa__${1}}$2 ";;
esac"
}
## aunset STEM KEY
## Remove KEY from the associative array named STEM.
aunset () {
eval "unset __aa__${1}__${2}
case $__aa__${1} in
*" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
esac"
}
(Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)
Shells with associative arrays
Some modern shells provide associative arrays: ksh93, bash ≥4, zsh. In ksh93 and bash, if a
is an associative array, then "${!a[@]}"
is the array of its keys:
for k in "${!a[@]}"; do
echo "$k -> ${a[$k]}"
done
In zsh, that syntax only works in ksh emulation mode. Otherwise you have to use zsh's native syntax:
for k in "${(@k)a}"; do
echo "$k -> $a[$k]"
done
${(k)a}
also works if a
does not have an empty key.
In zsh, you could also loop on both k
eys and v
alues at the same time:
for k v ("${(@kv)a}") echo "$k -> $v"
Shells without associative arrays
Emulating associative arrays in shells that don't have them is a lot more work. If you need associative arrays, it's probably time to bring in a bigger tool, such as ksh93 or Perl.
If you do need associative arrays in a mere POSIX shell, here's a way to simulate them, when keys are restricted to contain only the characters 0-9A-Z_a-z
(ASCII digits, letters and underscore). Under this assumption, keys can be used as part of variable names. The functions below act on an array identified by a naming prefix, the “stem”, which must not contain two consecutive underscores.
## ainit STEM
## Declare an empty associative array named STEM.
ainit () {
eval "__aa__${1}=' '"
}
## akeys STEM
## List the keys in the associatve array named STEM.
akeys () {
eval "echo "$__aa__${1}""
}
## aget STEM KEY VAR
## Set VAR to the value of KEY in the associative array named STEM.
## If KEY is not present, unset VAR.
aget () {
eval "unset $3
case $__aa__${1} in
*" $2 "*) $3=$__aa__${1}__$2;;
esac"
}
## aset STEM KEY VALUE
## Set KEY to VALUE in the associative array named STEM.
aset () {
eval "__aa__${1}__${2}=$3
case $__aa__${1} in
*" $2 "*) :;;
*) __aa__${1}="${__aa__${1}}$2 ";;
esac"
}
## aunset STEM KEY
## Remove KEY from the associative array named STEM.
aunset () {
eval "unset __aa__${1}__${2}
case $__aa__${1} in
*" $2 "*) __aa__${1}="${__aa__${1}%%* $2 } ${__aa__${1}#* $2 }";;
esac"
}
(Warning, untested code. Error detection for syntactically invalid stems and keys is not provided.)
edited Feb 2 '16 at 13:27
Stéphane Chazelas
309k57584945
309k57584945
answered Jan 29 '14 at 0:48
GillesGilles
542k12810971616
542k12810971616
add a comment |
add a comment |
I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]}
syntax:
$ typeset -A foo=([key1]=bar [key2]=baz);
$ echo "${!foo[@]}"
key2 key1
So, to iterate:
$ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
key2 : baz
key1 : bar
I found a nice, short tutorial on this here.
As pointed out in the comments below, associative arrays were added in bash
version 4. See here for a Linux journal article on the subject.
1
(bash version 4 only)
That's an important thing to note. Traditionally,bash
arrays are numeric only.
– Ricky Beam
Jan 28 '14 at 23:07
1
You might want to usetypeset
instead ofdeclare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.
– jlliagre
Jan 29 '14 at 1:00
add a comment |
I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]}
syntax:
$ typeset -A foo=([key1]=bar [key2]=baz);
$ echo "${!foo[@]}"
key2 key1
So, to iterate:
$ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
key2 : baz
key1 : bar
I found a nice, short tutorial on this here.
As pointed out in the comments below, associative arrays were added in bash
version 4. See here for a Linux journal article on the subject.
1
(bash version 4 only)
That's an important thing to note. Traditionally,bash
arrays are numeric only.
– Ricky Beam
Jan 28 '14 at 23:07
1
You might want to usetypeset
instead ofdeclare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.
– jlliagre
Jan 29 '14 at 1:00
add a comment |
I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]}
syntax:
$ typeset -A foo=([key1]=bar [key2]=baz);
$ echo "${!foo[@]}"
key2 key1
So, to iterate:
$ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
key2 : baz
key1 : bar
I found a nice, short tutorial on this here.
As pointed out in the comments below, associative arrays were added in bash
version 4. See here for a Linux journal article on the subject.
I'm not sure what you mean by store, but you can iterate over the keys using the ${!array[@]}
syntax:
$ typeset -A foo=([key1]=bar [key2]=baz);
$ echo "${!foo[@]}"
key2 key1
So, to iterate:
$ for key in "${!foo[@]}"; do echo "$key : ${foo[$key]}"; done
key2 : baz
key1 : bar
I found a nice, short tutorial on this here.
As pointed out in the comments below, associative arrays were added in bash
version 4. See here for a Linux journal article on the subject.
edited Jan 29 '14 at 2:23
answered Jan 28 '14 at 22:58
terdon♦terdon
132k32261441
132k32261441
1
(bash version 4 only)
That's an important thing to note. Traditionally,bash
arrays are numeric only.
– Ricky Beam
Jan 28 '14 at 23:07
1
You might want to usetypeset
instead ofdeclare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.
– jlliagre
Jan 29 '14 at 1:00
add a comment |
1
(bash version 4 only)
That's an important thing to note. Traditionally,bash
arrays are numeric only.
– Ricky Beam
Jan 28 '14 at 23:07
1
You might want to usetypeset
instead ofdeclare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.
– jlliagre
Jan 29 '14 at 1:00
1
1
(bash version 4 only)
That's an important thing to note. Traditionally, bash
arrays are numeric only.– Ricky Beam
Jan 28 '14 at 23:07
(bash version 4 only)
That's an important thing to note. Traditionally, bash
arrays are numeric only.– Ricky Beam
Jan 28 '14 at 23:07
1
1
You might want to use
typeset
instead of declare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.– jlliagre
Jan 29 '14 at 1:00
You might want to use
typeset
instead of declare
in your examples. That would make them portable between bash 4 and ksh93 which first implemented shell associative arrays.– jlliagre
Jan 29 '14 at 1:00
add a comment |
Shells without associative arrays
It's not that hard when keys are restricted to [0-9A-Za-z_]
(numbers, letters, underscore).
The trick is instead of storing to array[$key], store to variables array_$key.
Set:
eval "array_$key='$value'"
Get:
value=`eval echo '$'array_$key`
Note: Values cannot contain '
(single quote).
add a comment |
Shells without associative arrays
It's not that hard when keys are restricted to [0-9A-Za-z_]
(numbers, letters, underscore).
The trick is instead of storing to array[$key], store to variables array_$key.
Set:
eval "array_$key='$value'"
Get:
value=`eval echo '$'array_$key`
Note: Values cannot contain '
(single quote).
add a comment |
Shells without associative arrays
It's not that hard when keys are restricted to [0-9A-Za-z_]
(numbers, letters, underscore).
The trick is instead of storing to array[$key], store to variables array_$key.
Set:
eval "array_$key='$value'"
Get:
value=`eval echo '$'array_$key`
Note: Values cannot contain '
(single quote).
Shells without associative arrays
It's not that hard when keys are restricted to [0-9A-Za-z_]
(numbers, letters, underscore).
The trick is instead of storing to array[$key], store to variables array_$key.
Set:
eval "array_$key='$value'"
Get:
value=`eval echo '$'array_$key`
Note: Values cannot contain '
(single quote).
edited Jan 6 '17 at 4:49
answered Jan 6 '17 at 3:50
Marián ČernýMarián Černý
1677
1677
add a comment |
add a comment |
this works in bash
cert="first"
web="second"
declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
echo "first is" ${assoc_array[cert]}
echo "second is" ${assoc_array[web]}
OR
#loop
for i in "${assoc_array[@]}"
do
echo "$i"
done
No need to use eval afaik
New contributor
I believe that you've missed the point of the question.
– G-Man
4 hours ago
add a comment |
this works in bash
cert="first"
web="second"
declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
echo "first is" ${assoc_array[cert]}
echo "second is" ${assoc_array[web]}
OR
#loop
for i in "${assoc_array[@]}"
do
echo "$i"
done
No need to use eval afaik
New contributor
I believe that you've missed the point of the question.
– G-Man
4 hours ago
add a comment |
this works in bash
cert="first"
web="second"
declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
echo "first is" ${assoc_array[cert]}
echo "second is" ${assoc_array[web]}
OR
#loop
for i in "${assoc_array[@]}"
do
echo "$i"
done
No need to use eval afaik
New contributor
this works in bash
cert="first"
web="second"
declare -A assoc_array=(["cert"]="${cert}" ["web"]="${web}")
echo "first is" ${assoc_array[cert]}
echo "second is" ${assoc_array[web]}
OR
#loop
for i in "${assoc_array[@]}"
do
echo "$i"
done
No need to use eval afaik
New contributor
New contributor
answered 4 hours ago
JamesDJamesD
1
1
New contributor
New contributor
I believe that you've missed the point of the question.
– G-Man
4 hours ago
add a comment |
I believe that you've missed the point of the question.
– G-Man
4 hours ago
I believe that you've missed the point of the question.
– G-Man
4 hours ago
I believe that you've missed the point of the question.
– G-Man
4 hours ago
add a comment |
Thanks for contributing an answer to Unix & Linux Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f111397%2fassociative-arrays-in-shell-scripts%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
5
If you're trying to use associative arrays in a shell script it could be possible that your project is too complex for a shell script :)
– Martin von Wittich
Jan 29 '14 at 0:09
@MartinvonWittich why? I have a shell script that executes a SQL script on one of 3 possible DB schemas. The required schema is included in filename with an abbreviation. I need a mapping between this abbreviation and the real schema name. What better way than an associative array, considering the actual schema names (not the abbreviation) may differ between environments, so an array variable (whose values can be set just once) is perfect
– Slav
Nov 19 '14 at 14:16
2
@Slav I'm not arguing against associative arrays, just against shell scripts where such complexity is needed. But that's just my personal preference; I often catch myself starting to write a shell script and then immediately rewriting it in Perl when I realize that I'm exceeding a certain complexity threshold.
– Martin von Wittich
Nov 19 '14 at 22:50