Shell Command / Script To Write Simple Output On Screen Under Linux and UNIX

How do I simply write output from my shell script to the screen under Unix / Linux BASH shell?

Most modern shell such as bash, ksh and others comes with the echo and print in built commands. There is also printf (C like statement) command to format and display data on screen

echo command

All the parameters to the echo command are printed to the screen. For example:
echo "Hello World!"

You can add echo command to your shell script:

#!/bin/bash
echo "Memory information"
free -m
echo "Disk information"
df -h

printf command

You can also use printf command as follows
printf "Hello worldn"
Or use in a script as follows:

#!/bin/bash
print "Memory informationn"
free -m
printf "Disk informationn"
df -h

Where,

  • -n : It is a FORMAT controls the output as in C printf. n is use to print new line.

More options

You can print a variable value with echo or printf command. First define a variable called DDAY:
DDAY="15-Aug-2007"
Now print a variable using echo command:
echo "$DDAY"
Output:

15-Aug-2007

Now print a variable using echo command:
printf "$DDAYn"
Output:

15-Aug-2007

You can combine a shell variable with statements or command itself:

#!/bin/bash
DDAY="15-aug-2007" 
echo "D-Day is on $DDAY"
echo "Today is $(date)"
echo "Linux version : $(uname -r)"

$(uname -r) and/or $(date) are examples of command substitution. It allows the output of a command to replace the command name. The syntax comes in two different forms:

$(command-name)

OR

`command-name`

Preserving white spacing (blank space)

When you want the output to preserve your spacing enclose output in double quote:
$ echo "This is a test and today is $(date)"
Do not use single quote for command substitution:
$ echo 'This is a test and today is $(date)'
Sample outputs:

This is a test and today is $(date)

For more information read man page of printf and echo by typing the following commands:
$ man echo
$ man printf
$ man bash
$ man ksh

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.