Echo Command
Revision as of 19:05, 30 August 2009 by Admin (talk | contribs) (→Generating Output With printf command)
To display the value of a variable either use echo or printf command as follows:
echo $varName
OR
printf "%s\n" $varName
Generating Output With echo command
Use echo command to display a line of text or variable value. It offer no formatting option. It is good command to display simple output.
echo Command Examples
#!/bin/bash
# Display welcome message, computer name and date
echo "*** Backup Shell Script ***"
echo
echo "*** Run time: $(date) @ $(hostname)"
echo
# Define variables
BACKUP="/nas05"
NOW=$(date +"%d-%m-%Y")
# Let us start backup
echo "*** Dumping MySQL Database to $BACKUP/$NOW..."
# Just sleep for 3 secs
sleep 3
# And we are done...
echo
echo "*** Backup wrote to $BACKUP/$NOW/latest.tar.gz"
Generating Output With printf command
printf command format and display data on screen. However, printf does not provide a new line. You need to provide format string using % directives and escapes to format numeric and string arguments in a way that is mostly similar to the C printf() function. Use printf to generate formatted output.
printf Format Directives
From the printf man page:
FORMAT controls the output as in C printf. Interpreted sequences are: \" double quote \NNN character with octal value NNN (1 to 3 digits) \\ backslash \a alert (BEL) \b backspace \c produce no further output \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \xHH byte with hexadecimal value HH (1 to 2 digits) \uHHHH Unicode (ISO/IEC 10646) character with hex value HHHH (4 digits) \UHHHHHHHH Unicode character with hex value HHHHHHHH (8 digits) %% a single % %b ARGUMENT as a string with ‘\’ escapes interpreted, except that octal escapes are of the form \0 or \0NNN and all C format specifications ending with one of diouxXfeEgGcs, with ARGUMENTs converted to proper type first. Variable widths are handled.
printf Command Examples