Linux 如何在shell脚本中创建一个接收参数的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7655517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a function in shell script that receives parameters?
提问by Mosty Mostacho
I'm working on a shell script and I have some lines of code that are duplicated (copy pasted, let's say).
我正在处理一个 shell 脚本,我有一些重复的代码行(比方说复制粘贴)。
I want those lines to be in a function. What is the proper syntax to use?
我希望这些行在一个函数中。要使用的正确语法是什么?
And what changes shoud I do in order for those functions to receive parameters?
为了让这些函数接收参数,我应该做哪些更改?
Here goes an example.
这是一个例子。
I need to turn this:
我需要转这个:
amount=1
echo "The value is $amount"
amount=2
echo "The value is $amount"
Into something like this:
变成这样:
function display_value($amount) {
echo "The value is $amount"
}
amount=1
display_value($amount)
amount=2
display_value($amount)
It is just an example, but I think it's clear enough.
这只是一个例子,但我认为这已经足够清楚了。
Thanks in advance.
提前致谢。
采纳答案by Daniel Brockman
function display_value() {
echo "The value is "
}
amount=1
display_value $amount
amount=2
display_value $amount
回答by Alfred Huang
In a shell script, functions can accept any amount of input parameters. $1 stands for the 1st input parameter, $2 the second and so on. $# returns the number of parameters received by the function and $@ return all parameters in order and separated by spaces.
在 shell 脚本中,函数可以接受任意数量的输入参数。$1 代表第一个输入参数,$2 代表第二个,依此类推。$#返回函数接收到的参数个数,$@按顺序返回所有参数,用空格隔开。
For example:
例如:
#!/bin/sh
function a() {
echo
echo
echo
echo $#
echo $@
}
a "m" "j" "k"
will return
将返回
m
j
k
3
m j k