Unix Commands  «Prev  Next»
Lesson 5 Using variables with the sort command
Objective Incorporate a read-in variable into the sort command.

Incorporate read-in Variable into Sort Command

You can use a variable to provide any piece of the command. In the following script, the user is asked to enter the name of the file to sort and the column number to sort on. This information is read into variables and used to create a sort command. To include variable values in a script command, type the variable into the command like in the sort command at the bottom of the script below. The shell will translate the variable into its value and insert it into the text of the command.

$ cat sortfile
#! /bin/sh
echo “
Enter the name of the file you wish to sort: \c“
read $filename
echo “							 
Enter the column number you wish to sort on:
 read $col
 sort –t: +$col $filename

Using values that you obtain interactively from the user is very common in shell scripts. You'll use this technique with sort as well as other commands in the course project.
The next lesson shows how to pause a script by using the sleep command.

Sort Command
Sort Command

Using variables - Exercise

Click the Exercise button to practice using the sort command.
Using variables - Exercise