jmrq jmrq - 4 months ago 16
Bash Question

How to make bash color code stored in variable available to external script

I can't seem to find a solution to this particular problem I'm having using bash color codes stored as variables in an external file:


  1. I have a file containing a collection of color codes stored as variables that I want to make available to other scripts so that I can use the variable name instead of the color code in all my scripts.



colorCodeFile.sh

green='\033[1;32m'
red='\033[31m'
yellow='\033[1;33m'
endColor='\033[0m'



  1. I'm using source at the beginning of all my other script files to make the color variables available. This works fine and I get colored output.



aScriptUsingColorCodes.sh

source ~/colorCodeFile.sh
echo "this is ${red}red${endColor}"



  1. The catch is that for some reason the external script (aScriptUsingColorCodes.sh) that "calls" the source has to have an alias in my .bashrc file. If I make the script executable and put it in my path and remove the alias, the color variables are no longer available.



I don't understand why the color variables are available if I use an alias in my .bashrc file to run the script but are not available if I make the script executable and just run it from the command line without an alias.

Just to be clear, the executable scripts are in my path and they do run. The colorCodeFile.sh file contains variables with strings and functions and both of these are available and work fine when I use source to call them from an external script. But for the color code variables I just wind up getting the color code text ('\033[31m') instead of colored output.

I'm on a MAC if that matters.

Answer

Update colorCodeFile.sh like this:

$ cat colorCodeFile.sh
green=$(echo -e '\033[1;32m')
red=$(echo -e '\033[31m')
yellow=$(echo -e '\033[1;33m')
endColor=$(echo -e '\033[0m')

Or update aScriptUsingColorCodes.sh as:

echo -e "this is ${red}red${endColor}"