Bash Aliases – How to Extend Bash Aliases

aliasbashgrep

How to create an alias that actually extends another alias of the same name in
Bash?

Why:

I used to have GREP_OPTIONS set on .bashrc to something like this:

GREP_OPTIONS="-I --exclude=\*~"

I also had a script (let us say, setup-java.sh) which I would call before
working on some Java projects. It would contain the line:

GREP_OPTIONS="$GREP_OPTIONS --exclude-dir=classes"

If I also use Sass, then I would call setup-sass.sh which contains the line:

GREP_OPTIONS="$GREP_OPTIONS --exclude-dir=\*/.sass-cache"

But GREP_OPTIONS was
deprecated
and
apparently the standard solution is either create an alias or some script…

Best Answer

Bash stores the values of aliases in an array called BASH_ALIASES:

$ alias foo=bar
$ echo ${BASH_ALIASES[foo]}
bar

With parameter expansion we can get the either the last set alias (if exists) or the default value:

alias grep="${BASH_ALIASES[grep]:-grep} -I --exclude=\*~"

Now just do it on setup-java.sh:

alias grep="${BASH_ALIASES[grep]:-grep} -I --exclude=\*~  --exclude-dir=classes"

...and finally on setup-sass.sh:

alias grep="${BASH_ALIASES[grep]:-grep} -I --exclude=\*~ --exclude-dir=\*/.sass-cache"

If the three lines are called, we get what we want:

$ echo ${BASH_ALIASES[grep]:-grep}
grep -I --exclude=\*~ -I --exclude=\*~ --exclude-dir=classes -I --exclude=\*~ --exclude-dir=\*/.sass-cache
Related Question