In this section, we'll explore some more advanced string formatting techniques and examples to help you take your Bash scripting skills to the next level.
When dealing with large amounts of output, it's often helpful to format the text in a way that makes it easier to read and understand. Here's an example of how you can use string formatting to create a table-like output:
## Example data
files=("file1.txt" "file2.txt" "file3.txt" "file4.txt" "file5.txt")
sizes=(1024 2048 512 4096 8192)
## Format the output
echo -e "\e[1mFile\t\tSize (bytes)\e[0m"
echo "-----------------------------------"
for i in "${!files[@]}"; do
echo -e "\e[36m${files[$i]}\e[0m\t\e[33m${sizes[$i]}\e[0m"
done
Output:
File Size (bytes)
-----------------------------------
file1.txt 1024
file2.txt 2048
file3.txt 512
file4.txt 4096
file5.txt 8192
You can also use string formatting to conditionally apply styles based on the content of your variables or the script's output. This can be useful for highlighting important information or drawing attention to specific conditions. Here's an example:
## Example data
status="success"
message="Operation completed successfully."
## Apply formatting based on status
if [ "$status" = "success" ]; then
echo -e "\e[32m$message\e[0m"
else
echo -e "\e[31mError: $message\e[0m"
fi
Output:
Operation completed successfully.
Dynamic Prompt Customization
Another advanced use case for string formatting in Bash is the customization of your shell prompt. By incorporating variables and escape sequences, you can create a unique and informative prompt that reflects the current state of your system or environment. Here's an example:
## Set the custom prompt
PS1="\e[1m\e[35m[\u@\h \e[34m\w\e[35m]\$ \e[0m"
## The prompt will now look like this:
[user@hostname ~/documents]$
In this example, the prompt includes the username (\u
), hostname (\h
), and the current working directory (\w
), all formatted with different colors and styles.
By exploring these advanced string formatting techniques, you can create more visually appealing, informative, and user-friendly Bash scripts that will impress your colleagues and streamline your daily tasks.