we know perl gives us the facility to use hashes

%ages = ('Martin' => 28, 'Sharon' => 35, 'Rikke' => 29);

what if I want to do the same thing in shell script ??

thanks

Dani AI

Generated

Short answer for : shells are not all the same. Modern interactive shells (Bash 4+, ksh93, zsh, etc.) provide true associative arrays; classic POSIX /bin/sh does not. was pointing in the right direction; ’s command-substitution example is a different topic (capturing command output into a variable) rather than a hash data structure.

Bash example (works in Bash 4+):

declare -A ages
ages=( [Martin]=28 [Sharon]=35 [Rikke]=29 )

# read one value
printf '%s\n' "${ages[Martin]}"

# iterate keys
for name in "${!ages[@]}"; do
  printf '%s -> %s\n' "$name" "${ages[$name]}"
done

Always quote expansions (keys or values) and prefer a variable for any key that may contain spaces: k='Full Name'; echo "${ages[$k]}".

Portable alternatives for /bin/sh (no associative arrays): keep the mapping in a small lookup table or call out to awk/perl/python. Example using a here-doc + awk lookup (POSIX-friendly):

ages='
Martin:28
Sharon:35
Rikke:29
'

get_age() {
  printf '%s' "$ages" | awk -F: -v name="$1" '$1==name{print $2; exit}'
}

get_age Sharon   # prints 35

A common hack is name-prefixed variables (age_Martin=28) and a guarded eval to retrieve them; that works but needs careful input validation to avoid injection.

Notes and troubleshooting: check the shell version before using associative arrays ([ -z "$BASH_VERSION" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ] to detect old Bash). Associative arrays are not POSIX, key order is not guaranteed, and eval-based tricks can be unsafe—use an external tool (awk/python) for more complex maps.

Recommended Answers

All 3 Replies

At least in the bash and korn shells there are associative arrays, essentially hashes.

See this for bash and this for korn.

It depends upon what you want to do. In bash scripts you can assign the output of any other executable to a variable using the back-quote character, as in:

varname=`md5sum filename`

It depends upon what you want to do.

Sorry rubberman, but did you maybe reply in the wrong thread?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.