How can I take sort bash arguments alphabetically?
$ ./script.sh bbb aaa ddd ccc
and put it into an array such that I now have an array {aaa, bbb, ccc, ddd}
How can I take sort bash arguments alphabetically?
$ ./script.sh bbb aaa ddd ccc
and put it into an array such that I now have an array {aaa, bbb, ccc, ddd}
You can do:
A=( $(sort <(printf "%s\n" "$@")) )
printf "%s\n" "${A[@]}"
aaa
bbb
ccc
ddd
It is using steps:
arguments list i.e.
"$@"`I hope following 2 lines will help.
sorted=$(printf '%s\n' "$@"|sort)
echo $sorted
This will give you a sorted cmdline args.I wonder though why its needed :)
But anyway it will sort your cmdlines
Removed whatever was not required.
Here's an invocation that breaks all the other solutions proposed here:
./script.sh "foo bar" "*" "" $'baz\ncow'
Here's a piece of code that works correctly:
array=()
(( $# )) && while IFS= read -r -d '' var
do
array+=("$var")
done < <(printf "%s\0" "$@" | sort -z)