Make a Bash alias that takes a parameter?

后端 未结 20 1966
长发绾君心
长发绾君心 2020-11-21 06:53

I used to use CShell (csh), which lets you make an alias that takes a parameter. The notation was something like

alias junk=\"mv \\\\!* ~/.Trash\"

20条回答
  •  广开言路
    2020-11-21 07:04

    Both functions and aliases can use parameters as others have shown here. Additionally, I would like to point out a couple of other aspects:

    1. function runs in its own scope, alias shares scope

    It may be useful to know this difference in cases you need to hide or expose something. It also suggests that a function is the better choice for encapsulation.

    function tfunc(){
        GlobalFromFunc="Global From Func" # Function set global variable by default
        local FromFunc="onetwothree from func" # Set a local variable
    
    }
    
    alias talias='local LocalFromAlias="Local from Alias";  GlobalFromAlias="Global From Alias" # Cant hide a variable with local here '
    # Test variables set by tfunc
    tfunc # call tfunc
    echo $GlobalFromFunc # This is visible
    echo $LocalFromFunc # This is not visible
    # Test variables set by talias
    # call talias
    talias
    echo $GlobalFromAlias # This is invisible
    echo $LocalFromAlias # This variable is unset and unusable 
    

    Output:

    bash-3.2$     # Test variables set by tfunc
    bash-3.2$     tfunc # call tfunc
    bash-3.2$     echo $GlobalFromFunc # This is visible
    Global From Func
    bash-3.2$     echo $LocalFromFunc # This is not visible
    
    bash-3.2$     # Test variables set by talias
    bash-3.2$     # call talias
    bash-3.2$     talias
    bash: local: can only be used in a function
    bash-3.2$     echo $GlobalFromAlias # This is invisible
    Global From Alias
    bash-3.2$ echo $LocalFromAlias # This variable is unset and unusable
    

    2. wrapper script is a better choice

    It has happened to me several times that an alias or function can not be found when logging in via ssh or involving switching usernames or multi-user environment. There are tips and tricks with sourcing dot files, or this interesting one with alias: alias sd='sudo ' lets this subsequent alias alias install='sd apt-get install' work as expect (notice the extra space in sd='sudo '). However, a wrapper script works better than a function or alias in cases like this. The main advantage with a wrapper script is that it is visible/executable for under intended path (i.e. /usr/loca/bin/) where as a function/alias needs to be sourced before it is usable. For example, you put a function in a ~/.bash_profile or ~/.bashrc for bash, but later switch to another shell (i.e. zsh) then the function is not visible anymore. So, when you are in doubt, a wrapper script is always the most reliable and portable solution.

提交回复
热议问题