under_the_sea_salad
under_the_sea_salad

Reputation: 1834

Redefine echo for several scripts by calling a script that redefines echo

I have scripts A, B, C, etc. that I execute independently. I want to redefine how echo works for all scripts I am using.

I made the following script, preamble.sh, that I call from each script A, B, C:

#!/bin/bash

# Change the color of our output
# TODO: How to redefine echo for the parent caller?
PURPLE='\033[1;35m'
NC='\033[0m' # No Color
function echo() { builtin echo -e '\033[1;35m'$0'\033[0m'; }

unameOut="$(uname -s)"
case "${unameOut}" in
Linux*) machine=Linux ;;
Darwin*) machine=Mac ;;
CYGWIN*) machine=Cygwin ;;
MINGW*) machine=MinGw ;;
*) machine="UNKNOWN:${unameOut}" ;;
esac
echo "[Running on ${machine}...]"

When I do bash preamble.sh from another script, all I get is

preamble.sh

in purple (the color that I want echo to use in each script A, B, C, etc.).

I guess what ends up happening is echo is redefined correctly within preamble.sh but this is not how I expected it to work. When I call bash preamble.sh, preamble.sh gets executed but instead of telling me what machine it runs on, it just prints preamble.sh in purple because that must be the argument $0.

I realize I might be doing something that is not possibly to do directly.

How do I achieve what I am trying to achieve?

Upvotes: 1

Views: 69

Answers (1)

costaparas
costaparas

Reputation: 5237

The arguments to a function are $1, $2, ...

You want:

function echo() { builtin echo -e '\033[1;35m'$1'\033[0m'; }

not:

function echo() { builtin echo -e '\033[1;35m'$0'\033[0m'; }

Whether inside a function of not, $0 will remain the name of the script itself.

Edit: For your other question, you would need to run the script within the current shell for the changes to persist. You can do this using either

source preamble.sh

or

. preamble.sh

This is necessary since by default, the script will run in a new shell and any variables, functions, etc you define will not be visible.

Upvotes: 1

Related Questions