Unix Shell Scripts   «Prev  Next»
Lesson 5 A command to write to the screen
Objective Use the echo command to display data on the screen in Unix.

Using echo to Write to the Screen

Many shell scripts run “in the background” performing tasks like copying files, modifying configuration, or scheduling maintenance jobs. In other cases, a script must communicate with the user by printing status messages, instructions, or error information to the terminal.

The echo command prints text to the standard output stream (STDOUT), which normally appears on your screen. You use echo to provide feedback, explain what the script is doing, and guide the user through a workflow.

Basic echo Output

By default, echo writes the rest of the line to STDOUT and ends with a newline. If you use multiple echo commands, each typically prints on its own line:
echo The sample configuration file cannot be found.
echo Please contact your vendor for information.
The output looks like this:
The sample configuration file cannot be found.
Please contact your vendor for information.

Suppressing the Newline

Some shells support echo -n to suppress the trailing newline so the next output continues on the same line. For example:
echo -n "Contact your agent about the following file: "
echo "/etc/smb.conf"
Output:
Contact your agent about the following file: /etc/smb.conf

Modern note: echo options and escape handling can vary across shells and Unix platforms. When you need predictable formatting (especially for scripts you want to be portable), prefer printf.

Best Practice: Use printf for Predictable Formatting

printf is consistent across shells and gives you explicit control over newlines and formatting:
printf "%s\n" "The sample configuration file cannot be found."
printf "%s\n" "Please contact your vendor for information."
To print without a newline, omit \n:
printf "%s" "Contact your agent about the following file: "
printf "%s\n" "/etc/smb.conf"

Neighboring Topic: STDOUT vs STDERR

Scripts often separate normal messages from error messages. By convention:
  • STDOUT is for normal program output
  • STDERR is for warnings and error messages
You can send an error message to STDERR like this:
echo "ERROR: Missing configuration file." 1>&2
This becomes important later when you redirect output to files or pipelines.

Output commands are especially useful when the script’s behavior depends on decisions (for example, an if/then test) and you need to explain what branch was taken. You can also print a blank line for readability:
echo ""

Now that you can write to the screen, the next lesson shows how to read input from the keyboard.

SEMrush Software 5 SEMrush Banner 5