Reputation: 11
I am trying to write a Unix Shell Script that when executed it asks the user to enter 4 numbers and the script sort them numerically and print them out.
How can I do that?
Thank you for your help,
Andy
Upvotes: 0
Views: 5790
Reputation: 754920
You need to read the values and then echo them to the sort program.
echo -n "Enter 1st number: "
read a junk
echo -n "Enter 2nd number: "
read b junk
echo -n "Enter 3rd number: "
read c junk
echo -n "Enter 4th number: "
read d junk
{ echo $a; echo $b; echo $c; echo $d; } | sort -n
The only problem here is the notation used to suppress newlines after the echo
command. There are two notations - and different systems use different notations. The older notation is the echo -n
shown. The newer notation is:
echo "Enter Nth number: \c"
Which you need to use depends on your system, then.
The 'junk' variable collects any extra words after the first word on the input line. It's a form of paranoia, but means that if the user types '12 abc', then the single-letter variable gets just the '12' and not the rest. The code does not validate that the user entered a number. You could write a function to do that, and use it 4 times - it might as well take the prompt string and return a number.
Note that if you use bash
, the read
command is much more powerful and can do the prompting as well, side-stepping tricky issues with echo
notation for non-portable (to other than bash
) notations in read
instead. Except for the echo
notation, the code shown is portable to Bourne shell back to 7th Edition (or Version 7) UNIX (where echo
was not a shell built-in and it used the -n
option) and derivatives (Korn, Bash, POSIX, ...).
Upvotes: 1
Reputation: 25609
another way
read -p "Enter 1st number: " a
read -p "Enter 2nd number: " b
read -p "Enter 3rd number: " c
read -p "Enter 4th number: " d
printf "%s\n" $a $b $c $d | sort
Upvotes: 3
Reputation: 21910
You can use the "sort" utility, which reads from stdin and sorts each line lexicographycally.
As an example, you can check:
echo -e "1\n6\n2\n3" | sort -n
Which outputs:
1
2
3
6
Just output each number on a separate line, and pipe that into sort
Upvotes: 1
Reputation: 27149
Supposing your inputs are in $a
, $b
, $c
, $d
you can do this
printf "%s\n%s\n%s\n%s\n" $a $b $c $d | sort
Upvotes: 4