简体   繁体   中英

Using function parameters in a bash script alias

I have a bash script that I want to add an alias to that utilizes some function parameters. However for some reason the command is not working when I use passed parameters.

My alias:

alias pa='_pa() { php artisan "$1" "$2" "$3" "$4" "$5"; }; _pa'

Which should be able to consolidate php artisan cache:clear down to pa cache:clear

However this give me an input prompt, and not the expected command: php artisan cache:clear

Why am I unable to make an alias using this function?

Why are you doing that? Just change the alias to:

alias pa='php artisan'

Or throw away the alias altogether, and just use a function?

pa() {
  php artisan "$@"
}

Using "$@" will expand to as many arguments as you sent to pa

An alias does not take parameters. If you have an alias foo and write

foo x y z

the shell simply expands foo to what ever you have defined, so if for instance

alias foo='bar baz'

, the above line would be turned into

bar baz x y z

That's why it's called alias expansion and not alias invocation in the man page.

Further, your alias pa is pretty pointless. It does not do anything else than defining a function named _pa and then invoke it. Therefore, if in your shell no function of this name has been defined before, doing a

pa 10 20 30 40 50

is expanded to

_pa() { 
     php artisan "$1" "$2" "$3" "$4" "$5"
}
_pa 10 20 30 40 50

and thus causes the function _pa to spring into existence and also invoke this function. As we have alias expansion, those remaining parameters (10, 20,...) are appended to the line and end up as parameter to the function _pa.

Basically, with every repeated use of your alias pa , you throw away the old _pa and create it freshly. It is not forbidden to do this, but a cleaner solution would be to define the function separately, and if you want to have a second name for this function for whatever reason, define the alias after:

_pa() { 
     php artisan "$1" "$2" "$3" "$4" "$5"
}
alias pa=_pa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM