Certainly! Below is a simple Bash script that reads data from standard input (stdin) character by character. For each character, it determines its ASCII value and uses that value to set the background color using the ANSI escape sequence \033[48;5;{COLOR}m. It then prints a space with the specified background color. Finally, it resets the terminal colors after processing the input.
Bash Script: colorize.sh
#!/bin/bash
# Function to reset terminal colors
reset_colors() {
printf "\033[0m\n"
}
# Trap to ensure colors are reset if the script is interrupted
trap reset_colors EXIT
# Read input character by character
while IFS= read -r -n1 char; do
# Get the ASCII value of the character
# Using printf to convert character to its ASCII number
ascii=$(printf '%d' "'$char")
# Ensure the color code is within 0-255
color=$(( ascii % 256 ))
# Print a space with the background color
printf "\033[48;5;%sm " "$color"
done
# Reset terminal colors after processing
reset_colors
How to Use the Script
-
Save the Script:
Save the above script to a file, for example, colorize.sh.
-
Make the Script Executable:
chmod +x colorize.sh
-
Run the Script with Input:
You can pass input to the script via a pipe or by typing directly.
-
Using a Pipe:
echo "Hello, World!" | ./colorize.sh
-
Typing Directly:
./colorize.sh
Then type your input and press Ctrl+D to signify the end of input.
Explanation of the Script
Example
Running the script with the input "ABC" would display three colored blocks corresponding to the ASCII values of A, B, and C.
echo "ABC" | ./colorize.sh
This will output three spaces with background colors based on the ASCII values:
A (65) → color 65
B (66) → color 66
C (67) → color 67
Notes
-
Terminal Compatibility:
Ensure your terminal supports 256 colors. Most modern terminals do, but some older ones might not.
-
Color Mapping:
The mapping is directly based on ASCII values. Depending on your input, colors may repeat or wrap around if ASCII values exceed 255.
-
Customization:
You can modify the script to adjust how colors are mapped or displayed based on your preferences.
Feel free to enhance the script further based on your specific needs!