4th Floor, 4 Tabernacle Street London EC2A 4LU

Shell, KSH Read Variables

Read in a Variable

From a user we read with: read var. Then the users can type something in. One should first print something like:
[bash] print -n “Enter your favorite haircolor: “;
read var;
print “”.
[/bash]

The -n suppresses the newline sign.
Read into a File Line for Line

To get each line of a file into a variable iteratively do:
[bash] { while read myline;do
# process $myline
done } < filename
[/bash]

To catch the output of a pipeline each line at a time in a variable use:

[bash] last | sort | {
while read myline;do
# commands
done }
[/bash]

Special Variables

$# Number of arguments on commandline.
$? Exit status of last command.
$$ Process id of current program.
$! Process id of last backgroundjob or background function.
$0 Program name including the path if started from another directory.
$1..n Commandline arguments, each at a time.
$* All commandline arguments in one string.