Skip to content

Instantly share code, notes, and snippets.

@JrCs
Last active December 8, 2015 18:35
Show Gist options
  • Save JrCs/fac5596df360779b8a94 to your computer and use it in GitHub Desktop.
Save JrCs/fac5596df360779b8a94 to your computer and use it in GitHub Desktop.
Find shortest string in an array with bash
#!/bin/bash
shortest()
{
local arrayname=${1:?Array name required} varname=${2:-shortest}
local IFS= string e
eval "array=( \"\${$arrayname[@]}\" )"
shortest=${array[0]}
for e in "${array[@]}"; do
[[ ${#e} -lt ${#shortest} ]] && shortest=$e
done
[[ "$varname" != shortest ]] && eval "$varname=${shortest}"
}
declare -a toto=( s1.free.domain.org free.domain.org s2.free.domaine.org )
shortest toto
echo $shortest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment