I would like to query and store the current terminal color pair in BASH e.g.:
#!/bin/bash
#some ANSI colour escape sequences
red="\033[0;31m"
grn="\033[0;32m"
blu="\033[0;34m"
def="\033[0;00m" # default
echo -e "Change to ${red} red to ${def} default to ${blu} blue."
# now store the current color (which happens to be blue) e.g.:
cur=????
echo -e "Change to ${grn} green and back to what I had before ${cur}"
echo -e "This would be in blue if variable cur contained e.g.: 0;34m."
echo -e "Back to default${def}"
exit 0
The answer that eludes me is how to capture the current color
cur=????
Then go in your Terminal settings -> Preferences -> Profiles -> Text -> Display ANSI colors. Open a new terminal and you should be ready to go! Save this answer.
For example, if you wanted to print green text, you could do the following: #!/bin/bash # Set the color variable green='\033[0;32m' # Clear the color after that clear='\033[0m' printf "The script was executed ${green}successfully${clear}!"
You can get the color code by taking the final digit of the ANSII code (32 for green foreground, 42 for green background; 31 or 41 for red, and so on).
The question was about the current color, not the cursor position.
Both are "nonstandard" (though the latter, cursor position report is implemented by anything which has a valid claim to "VT100 emulator").
However, xterm implements a set of escape sequences referred to as dynamic colors, which predate the ANSI color functionality. Those set the working colors including text foreground and background. I modified this in 2002 to allow an application to send the sequence with a "?" rather than a color to tell xterm to return the color value, e.g.,
OSC 1 1 ? ST
using the notation given in XTerm Control Sequences
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With