0

I have two aliases watchExpand and l. I know that you can make bash expansion work with aliases by placing a trailing space like so:

alias watchExpand='watch '

l is aliased to ls -larthiF --context. So when I type the command watchExpand l it works like a charm.

However if I supply a parameter to watchExpand command, e.g.

watchExpand -n 1 l

My l alias no longer works. How can I get bash expansion after arguments?

  • aliases don't expand unless they're the first word in a line – Jeff Schaller Oct 21 '16 at 18:41
  • 1
    bash reference says: "If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion" – Jeff Schaller Oct 21 '16 at 18:43
  • I'm not sure this is a good idea, but if the question is: "how can I expand every parameter to an aliased command in case that parameter is also an alias?" is to make your aliased command (watchExpand) a function that loops over its parameters and does so manually – Jeff Schaller Oct 21 '16 at 18:49
1

Here's the bad idea I think you're asking for:

function watchExpand() {
  e=""
  for param in $@
  do
    if alias $param >/dev/null 2>&1
    then
      exp=$(alias $param | cut -d= -f2| sed -e s/^\'// -e s/\'\$//)
      e+=" $exp"
    else
      e+=" $param"
    fi
  done
  watch $e
}
| improve this answer | |
0

I figure out the solution with my way.

Firstly, i create a function called "addExpand" to add alias/fucntion easier if i want.

xb@dnxb:/tmp/t$ type -a addExpand
addExpand is a function
addExpand () 
{ 
    echo -e "#!/bin/bash\nshopt -s expand_aliases\n. ~/.bash_aliases 2>/dev/null\n$1"' "$@"' | sudo tee /usr/bin/e_"$1";
    sudo chmod +x /usr/bin/e_"$1"
}
xb@dnxb:/tmp/t$ addExpand l
#!/bin/bash
shopt -s expand_aliases
. ~/.bash_aliases 2>/dev/null
l "$@"

After i run addExpand l, alias l will created as an executable file named /usr/bin/e_l with following content:

xb@dnxb:/tmp/t$ cat /usr/bin/e_l
#!/bin/bash
shopt -s expand_aliases
. ~/.bash_aliases 2>/dev/null
l "$@"

Now enjoy to use expand version of alias/function:

xb@dnxb:/tmp/t$ watch --color -n 1 e_l /tmp //works like a charm !!!
xb@dnxb:/tmp/t$ 

Note:

[1] e_l, prefix with 'e_' to imply it's expansion version of command.

[2] I feel too heavy to perform sourcing every seconds if run with watch -n 1. I might need to find a way to solve this problem.

[3] Another disadvantage is it doesn't resolve alias recursively.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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