How to expand aliases on any invocation of /bin/bash

2

0

Any of you know a way to expand an alias whenever a new shell is invoked (from any place)?

For example, my alias is:

alias ls='ls -F'
  • Now if I invoke it in

    grep -l ramesh | xargs ls
    

    … here I should get the ls -F output.

  • If I do for e.g.

    cut -f 1 `ls test*`
    

    I should get a ls -F substitution.

Within a shell script, there is this option shopt -s expand_aliases but how do I get it everywhere?

Telex

Posted 2011-10-12T09:00:52.933

Reputation: 43

Answers

4

As ls isn't actually invoked by your shell in the first example, the alias doesn't work with xargs.

Aliases aren't exported to subshells, that's why the second example fails.

Since aliases are evaluated after a line is read, you cannot e.g. foo=$( alias ls='ls -l' ; ls ) either.


To get the desired effect in bash only, you can use functions, e.g.

function ls { /bin/ls -F "$@" ; }

you can add these to subshells like this to make it work:

ret=$( function ls { /bin/ls -l "$@" ; } ; ls )

The proper solution to have it work in all places where any program executes ls, place a script named ls before the actual ls in the search $PATH that calls the actual ls with -F parameter.

#!/bin/bash
/bin/ls -F "$@"

Save as /usr/local/bin/ls and export $PATH=/usr/local/bin:$PATH.

Be aware of programs that use /bin/ls hard-coded, and programs that parse the output of ls and will fail when it's a different format than expected.

Daniel Beck

Posted 2011-10-12T09:00:52.933

Reputation: 98 421

Thanks for the response. The proper solution looks good :-). I tried it for some of the frequent aliases i intend to use within vim and xargs and it works fine. Great – Telex – 2011-10-12T11:29:37.640

1@John: Yes, done – Telex – 2011-10-12T14:09:45.940