Shell script braces and variables
Been scratching my head with braces and variables.
I have a text file named shell-colors that defines escape sequences and colors: ESC="\033[" BOLDRED="${ESC}01;31m" BOLDGREEN="${ESC}01;32m" BOLDYELLOW="${ESC}01;33m" BOLDBLUE="${ESC}01;34m" BOLDMAGENTA="${ESC}01;35m" BOLDCYAN="${ESC}01;36m" BOLDWHITE="${ESC}01;37m" COLOR_RESET="${ESC}00m" I source this file in interactive shell scripts. When I want to add colors in a script I use braces to define the color variable: ${BOLDYELLOW}This is a warning.${COLOR_RESET} Works greats. I want to create a subroutine in a script where I can send messages but vary the color. For example: MSG="Some text." Color_Message BOLDYELLOW Color_Message () { SOMECOLOR=$1 ${SOMECOLOR}$MSG${COLOR_RESET} } When I use, say, ${BOLDYELLOW} directly I get the color but when I pass the text string BOLDYELLOW I can't reformat that string into the variable ${BOLDYELLOW}. That is, ${BOLDYELLOW}$MSG${COLOR_RESET} works but ${SOMECOLORSTRING}$MSG${COLOR_RESET} does not work. How do I reformat the string as a variable? Thanks much. |
you'd use:
Color_Message ${BOLDYELLOW} If you really want to use "names" rather than the values, you can look at doing an extra evaluation (using eval, for example). e.g. Code:
Color_Message () { |
Quote:
|
I think that can also be done like this:
Code:
# usage: color_message <message> <colorname> Code:
function log_message { |
Quote:
I use the shell-colors container in almost all of my shell scripts and likewise in the script I was revising. In my revisions I noticed a lot of repetitive code with respect to user informational messaging. I consolidated that repetition into a simple function I could call. Much nicer and more efficient, of course. In that script I noticed I had about 8 or 9 snippets where I could not use my new function, but if I could pass the desired color as an argument/parameter I could augment my new function with an elif statement. I could have created a separate color functions for this one script but that would have been less efficient than just using the color variables directly inline. |
Since you're after efficiency I also thought about sharing my codes. This is part of playshell:
log.sh Code:
include available.sh Code:
# console.sh Code:
include console.sh |
All times are GMT -5. The time now is 08:24 AM. |