Print Strings in Bash
In Bash, echoing and printing text are common operations used to display information on the terminal. Both "echo" and "printf" commands are often used for this purpose.
Echo Command
The echo command is one of the simplest ways to display text in the terminal. It automatically adds a newline character at the end of the output.
This will output:
You can also use the -e option with echo to enable interpretation of backslash escapes. For example:
This will output:
Command Substitution
You can use command substitution within echo to include the output of another command. For example:
This will output:
Variables
Store text in variables and then print them using echo. For example:
This will output:
Redirection
You can redirect the output of echo to a file using > or append to an existing file using >>. For example:
This appends the text to the log.txt file.
Printf Command
The printf command provides more advanced formatting options compared to echo. It allows you to control the format of the output using placeholders.
This will output:
In the printf command:
You can use various other format specifiers with printf to control the appearance of the output.
This will output:
Here, %.2f specifies that the floating-point number should be displayed with two decimal places.
Points to Remember:- Avoid exceeding terminal width to prevent text wrapping.
- Use quotes for multi-word arguments or special characters.
- Practice responsible scripting and avoid harmful uses of text manipulation.
Conclusion
Both echo and printf are used for printing text in Bash, but printf offers more advanced formatting options. Choose the one that best fits your needs based on the simplicity or complexity of the output you want to display.