2

for example, if I want to write a script that get strings as arguments, and I want to insert them to array array_of_args and then I want to sort this array and to make sorting array.

How can I do it?

I thought to sort the array (and print it to stdout) in the next way:

array_of_args=("$@")
# sort_array=()
# i=0
    for string in "${array_of_args[@]}"; do
        echo "${string}"
    done | sort

But I don't know how to insert the sorting values to array ( to sort_array)..

0

1 Answer 1

1

You can use following script to sort input argument that may contain whitespace, newlines, glob characters or any other special characters:

#!/usr/bin/env bash

local args=("$@") # create an array of arguments
local sarr=()     # initialise an array for sorted arguments

# use printf '%s\0' "${args[@]}" | sort -z to print each argument delimited
# by NUL character and sort it

# iterate through sorted arguments and add it in sorted array
if (( $# )); then
   while IFS= read -rd '' el; do
      sarr+=("$el")
   done < <(printf '%s\0' "${args[@]}" | sort -z)
fi

# examine sorted array
declare -p sarr
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks, yes adding -r twice was a typo
Hmm. Offhand, I don't see an answer this good on the longstanding duplicate -- there's at least one that gets close as an aside/afterthought, but nowhere it appears to be the primary recommendation. Might copy this there?
@Jor.Mal, (( ${#arr[@]} )) && { printf '%s\n' "${arr[@]}" | sort; } is your one line of code.
@anubhava, ...one caveat there is that it'll print a single newline if the array is empty, hence the (( ${#arr[@]} )) check to suppress output in the empty case. S'ppose that's actually a problem with the original/primary code in the answer too (changing args=( ) to sarr=( '' )).
Use: for element in "${arr[@]:1}"; do ...done
|