如何将位置参数传递给函数 [英] How to pass positional parameters to a function
本文介绍了如何将位置参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用bash脚本.我做了这个简单的脚本
I was trying things with bash scripts. I made this simple script
#!/bin/bash
function myfun()
{
for item in `seq 1 5`
do
echo "$item $1 $2"
done
}
myfun
但是没有运气.如果我按如下所示更改它,一切似乎都很好,
but no luck. If I change it like this as below, everything seems to be fine,
#!/bin/bash
a=$1
b=$2
function myfun()
{
for item in `seq 1 5`
do
echo "$item $a $b"
done
}
myfun
看来,参数(位置参数)在shell的函数内部不起作用.我有做错什么吗?我还在学习东西.那么你能解释为什么会这样吗?
It looks like arguments (positional parameters) do not work inside function in shell. Am I doing any mistake? I am still learning things. So can you explain why is it so?
推荐答案
在函数内部,$ 1和$ 2给出函数参数而不是脚本参数.
Inside a function, $1 and $2 give the function arguments and not the script parameters.
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html
这篇关于如何将位置参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文