Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output arguments in sorted order

Tags:

bash

sorting

I need to write a bash script that prints out its command line arguments in sorted order, one per line.

I wrote this script and it works fine, but is there any other way? Especially without outputting it to a file and sorting.

#!/bin/bash

for var in $*
do
    echo $var >> file
done

sort file
rm file

Test run of the program:

$ script hello  goodbye zzz aa
aa
goodbye
hello
zzz
like image 812
SharkTiles Avatar asked Jul 17 '12 17:07

SharkTiles


2 Answers

You can pipe the for-loop to sort, or just do

printf '%s\n' "$@" | sort
like image 106
geirha Avatar answered Sep 24 '22 01:09

geirha


#!/bin/bash

for var in "$@"; do
    echo "$var"
done | sort

You want to use $@ in quotes (instead of $*) to accommodate arguments with spaces, such as

script hello "goodbye, cruel world"

The pipe gets rid of the need for a temporary file.

like image 40
chepner Avatar answered Sep 26 '22 01:09

chepner