Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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.

share|improve this answer
    
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 Oct 12 '11 at 11:29
    
@Ramesh: then accept this answer –  Prince John Wesley Oct 12 '11 at 12:13
1  
@John: Yes, done –  Telex Oct 12 '11 at 14:09
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.