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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
@Carbonic-acid now that's a true beauty
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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.