bash alias with parameters

23,256

This is not the way bash aliases work, all the positional parameters in the bash aliases are appended at the end of the command rather than the place you have defined. To get over it you need to use bash functions.

An example will make you more clear :

$ cat file.txt 
foo
$ cat bar.txt 
foobar
spamegg
$ grep -f file.txt bar.txt 
foobar

$ alias foo='grep -f "$1" bar.txt'  ## Alias 'foo'
$ foo file.txt 
grep: : No such file or directory

$ spam () { grep -f "$1" bar.txt ;}  ## Function 'spam'
$ spam file.txt 
foobar

As you can see as the first argument in case of alias foo is being added at the end so the command foo file.txt is being expanded to :

grep -f "" bar.txt file.txt

while in case of function spam the command is correctly being expanded to :

grep -f file.txt bar.txt

So in your case, you can define a function like :

gr () { xmgrace -legend load -nxy "$@" -free -noask & ;}
Share:
23,256

Related videos on Youtube

muru
Author by

muru

Updated on September 18, 2022

Comments

  • muru
    muru over 1 year

    I would like to swap from csh to bash, then I have to set the .bashrc with the commands I use. Translating alias with parameters seems to be not easier as I believed. csh:

    alias gr 'xmgrace -legend load -nxy \!* -free -noask&'
    

    the param \!* means all params on the command line; Then I tried for bash:

    alias gr='xmgrace -legend load -nxy $@ -free -noask&'
    alias gr='xmgrace -legend load -nxy $(@) -free -noask&'
    

    But neither worked.

    The other issue comes from memorizing the current directory csh:

    alias t 'set t=\`pwd\``;echo $t'
    alias tt 'cd $t'
    

    I tried a lot of things but without any results.

    • fedorqui
      fedorqui over 8 years
      alias cannot use parameters. for this you need to write a function.
    • heemayl
      heemayl over 8 years
      @muru I was looking for a suitable dupe but couldn't find one..the answer from the one you have referred to does not provide the whole scenario IMHO..
    • muru
      muru over 8 years
      @heemayl and your answer does?
    • heemayl
      heemayl over 8 years
      @muru well, i have tried to make it more clarified....if you don't feel the same its allright..i thought i should tell you what i felt prior to answering, nothing more :)
  • alex
    alex almost 6 years
    Can the function be saved to a .bashrc file? If so, can it be aliased from the .bashrc file?
  • heemayl
    heemayl almost 6 years
    @alex Yes, the function can be saved in ~/.bashrc. Not sure what you meant in your second question.
  • alex
    alex almost 6 years
    I meant something like "can that function use alias to be invoked on the shell", like alias validate_foo=validate_bar(); (turns out the answer is no, it doesn't have to leverage alias as a prerequisite of being invoked on the shell). Thanks!