简体   繁体   中英

Linux how to sort parameters

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 .

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.

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
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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM