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
You can pipe the for-loop to sort, or just do
printf '%s\n' "$@" | sort
#!/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With