Skip to content

Instantly share code, notes, and snippets.

@codeFareith
Created July 26, 2014 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeFareith/ac69dd39cd3000444a9d to your computer and use it in GitHub Desktop.
Save codeFareith/ac69dd39cd3000444a9d to your computer and use it in GitHub Desktop.
Bash-Scripts

Bourne Again Shell

get value by array key


Usage

usage: get KEY ${ARRAY[@]};

Script

#!/bin/bash

function get() {
	local key="${1}";
	local val;

	while [ "${1}" != '' ]; do
		shift;
		if [ "${1%%:*}" == "${key}" ]; then
			val="${1#*:}";
			echo "${val}";
			return 0;
		fi;
	done;
	return 1;
}

Example

ARRAY=(
    "foo:bar"
    "key:val"
);
val=$( get foo ${ARRAY[@]} );
echo "${val}";

# Output
bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment