echo and printf
Basic echo
echo is the simplest way to print text: it writes its arguments to standard output separated by single spaces and adds a trailing newline. Multiple arguments are joined with a single space regardless of how many spaces separated them in the source.
Example: Basic echo
#!/bin/bash
echo "Hello, Bash!"
echo Hello Bash
Login to try C/C++/Java/PHP code in the editor
echo Flags: -n and -e
echo -n prints text without the trailing newline, useful when you want to build a line piece by piece. echo -e turns on interpretation of backslash escape sequences such as \n (newline) and \t (tab), which are otherwise printed literally.
Warning: Plain echo "a\nb" (without -e) prints the literal characters \n, not an actual newline.
Example: echo Flags: -n and -e
#!/bin/bash
echo -n "No newline here... "
echo "and this continues on the same line"
echo -e "Column1\tColumn2\nRow2Col1\tRow2Col2"
Login to try C/C++/Java/PHP code in the editor
printf Basics
printf takes a format string as its first argument and substitutes remaining arguments into placeholders like %s (string) or %d (integer). Unlike echo, it never appends a newline automatically, so you write \n explicitly wherever you want one.
Example: printf Basics
#!/bin/bash
printf "Name: %s, Age: %d\n" "Ada" 36
printf "Pi is roughly %.2f\n" 3.14159
Login to try C/C++/Java/PHP code in the editor
printf for Repeated/Formatted Output
printf recycles its format string over extra arguments if you give it more values than placeholders, which is handy for printing lists in a consistent format without a loop. This also makes printf more predictable than echo when the data being printed might contain special characters.
Example: printf for Repeated/Formatted Output
#!/bin/bash
printf "Item: %s\n" apple banana cherry
Login to try C/C++/Java/PHP code in the editor
- Assuming
echobehaves identically everywhere; its handling of backslash escapes and flags like-ediffers between shells and even between Bash versions/builtins vs/bin/echo. - Forgetting that
printfdoes NOT automatically add a newline, unlikeecho, so output from consecutiveprintfcalls can run together on one line. - Using
echoto print user-controlled or variable data that might start with a dash (like-n), whichechocan misinterpret as a flag instead of text.
echoprints its arguments followed by a newline by default.echo -nsuppresses the trailing newline;echo -eenables interpretation of backslash escapes like\nand\t.printfnever adds a newline automatically -- you must include\nyourself in the format string.printfsupports format specifiers like%s,%d, and%.2f, similar to C's printf, giving precise control thatecholacks.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: