[Embedded development Linux common command series 14.1 -- .bashrc definition function]


Previous article: [embedded development Linux common command series 14 – the difference between source hello.sh and ./hello.sh]

Article directory

.bashrc defines functions

When defining an alias in a .bashrc file, you generally cannot pass parameters directly. Aliases are shorthand for creating commands; they do not support parameters. However, if you need to use parameters, you can define a shell function and place it in your .bashrc file.

For example, if you want to create an alias to use the grep command, and want to pass an argument (such as the pattern to search for), you would do it in .bashrc Do this:

# 在 .bashrc 文件中定义一个函数作为别名 
mygrep() {
    
     
	grep "$1" "${@:2}" 
} 
# 每次打开新的 shell 时,重新加载 .bashrc 
alias reloadbashrc='source ~/.bashrc' 

In this example, the first argument of the mygrep function"$1" is used as the pattern for grep while "${@:2}" represents all parameters starting from the second parameter, which will be passed to the grep command.

After saving your .bashrc file, you will need to reload it for the changes to take effect. You can close and reopen your terminal, or run the following command in the terminal:

source ~/.bashrc 

Now you can use the mygrep function like an alias and pass arguments to it:

mygrep "pattern_to_search" /path/to/file_or_directory 

This calls grep and searches for the specified pattern. This way you can use functions to simulate aliases that receive arguments.

Example 2:
Since every time you log in to the FPGA on the server, you need to execute the ssh sam@fpga$1.armtech.cn command, which is very It's trouble. So the function is defined in .bashrc, and which FPGA to log in to is selected based on the parameters passed in. fpga

function fpga {
    
    
        sshpass -p Sam\$xxx ssh sam@fpga$1.armtech.cn
}

This type of sshpass command is used to enter a password on the command line.

Previous article: [embedded development Linux common command series 14 – the difference between source hello.sh and ./hello.sh]

Guess you like

Origin blog.csdn.net/sinat_32960911/article/details/135010929