echo is used to direct a variable or text to the standard output of a shell script. The echo command has the following options:
-e interpret backslashed characters
-E don't interpret backslashed characters
-n omit the final newline
The read command is used to read user input into a shell script. It has the syntax:
The input the user enters is stored in the variable inputvariable.
echo "Enter a filename."; read filename; if [ ! -e $filename ] then echo "$filename does not exist." fi
printf is like echo, except that it allows for formatted text. It also allows for several escape sequences (not all of which work with echo, I've found).
The syntax for printf is:
printf "text %format-specifier text" formatted;
Some of the format specifiers used in printf are:
%d - Decimal integer
%.preE - Exponential (scientific) notation with pre precision.
%.pref - Floating point number to pre decimal places
%o - Octal value
%u - Unsigned decimal value
%x - Lowercase hexidecimal value
%X - uppercase hexidecimal value
\a Alert sound
\c Omit final newline
\f Form feed
\t Tab character
\v Vertical tab
\0nnn 7-bit ASCII character for octal value nnn
\xHH 7-bit ASCII character for hexidecimal value HH
#!/bin/bash printf "%.3E\n" 1500000; printf "%.5f\n" 4.95; printf "%x\n" 143; printf "%u\n" -1; printf "\x7e\n";
1.500E+06 4.95000 8f 18446744073709551615 ~
There are six kinds of I/O redirection in Unix. Four of them are familiar to most Unix users: the >, <, >>, and | redirectors. Here is a rundown:
> Send the standard output of the preceding command to the following file, overwriting its original contents
< Get standard input for the preceding program from the following file
>> Append the standard output of the preceding command to the following file
| send the standard output of the preceding command to the following program, known as piping
There are two other types of I/O redirectors: here-documents and file descriptors.
A here-document is when you write a macro script inside a shell script to control an interactive program, such as ed or ftp. The syntax is as follows:
program $input << EndOfScript; program commands EndOfScript;
Here, EndOfScript is the marker used to terminate the macro script.
As an example, here is a here-document script that uses ed to append text to a file:
#!/bin/bash ed $1 << EndOfScript; a $2 . w q EndOfScript
A file descriptor is something that is generally only of concern to systems programmers as it controls the low level functioning of programs. Every time a Unix program is run, there are three file descriptors involved: standard output, standard input, and standard error. The first is called stdin and is given the number 0. The second is called stdout and is given the number 1. The third is called stderr and is given the number 2. The following script sends the standard output of cd / to the file file1.txt:
#!/bin/bash echo "Text to add to file1.txt."; cd / > ~/Desktop/file1.txt 1>&0; echo $0;
That concludes my tutorial.