5

When I want to run my parameter with -sort after it, I need to sort all the other parameters that I mention with it. Example

. MyScript.sh -sort Tree Apple Boolean

The output should need to be

Apple 
Boolean
Tree

I tried to make an array and run through all the parameters but this didn't work out

Array=()
while (( "$#" ))
do
  Array += "$1"
  shift
done

This also had the problem that I couldn't ignore the -sort.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2252399
  • 153
  • 1
  • 1
  • 8

3 Answers3

7

Try this script:

#!/bin/bash

if [ "$1" = "-sort" ]; then
    shift;
    echo "$@" | tr ' ' '\n' | sort | tr '\n' ' ';
    echo;
else
    echo "$@";
fi

Explanation: the first if checks if the first argument is -sort. If it is, it shifts the arguments, so -sort goes away but the other arguments remain. Then the arguments are run through tr which turns the space separated list into a newline separated one (which sort requires), then it pipes that through sort which finally prints the sorted list (converted back to space-separated format). If the first argument is not -sort, then it just prints the list as-is.

  • Somehow I would have guessed that if the `-sort` option were not present, the `Tree Apple Boolean` should have been output in just that order. If that is what really needed, put the shown `echo` into the `if` block, and make an `else` where output is done without the sort – mogul Jun 02 '13 at 06:25
  • @Carbonic-acid now that's a true beauty – mogul Jun 02 '13 at 06:34
0

You can also do something like this and add to it as per your requirements. :

#!/bin/bash

if [ "$1" == "-sort" ]; then
    shift;
    my_array=("$@")
    IFS=$'\n' my_sorted_array=($(sort <<<"${my_array[*]}"))
    printf "%s\n" "${my_sorted_array[@]}"
else
    echo "$@"
fi

Test:

[jaypal:~] ./s.sh -sort apple doggie ball cat
apple
ball
cat
doggie
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
0
if [ "X$1" = "X-sort" ]
then shift; printf "%s\n" "$@" | sort
else        printf "%s\n" "$@"
fi

The then clause prints the parameters, one per line (trouble if a parameter contains a newline), and feeds that to sort. The else clause lists the parameters in their original (unsorted) order. The use of X with test probably isn't 100% necessary, but avoids any possibility of misinterpretation of the arguments to test (aka [).


One problem with your code fragment is the spaces around the += in:

Array += "$1"

Shell does not like spaces around the assignment operator; you needed to write:

Array+="$1"
Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278