shell(ksh) 脚本上的函数行为
以下是程序的 2 个不同版本:
this
程序:
#!/usr/bin/ksh
printmsg() {
i=1
print "hello function :)";
}
i=0;
echo I printed `printmsg`;
printmsg
echo $i
输出:
# ksh e
I printed hello function :)
hello function :)
1
和
程序:
#!/usr/bin/ksh
printmsg() {
i=1
print "hello function :)";
}
i=0;
echo I printed `printmsg`;
echo $i
输出:
# ksh e
I printed hello function :)
0
以上 2 个程序之间的唯一区别是 printmsg
在上面的程序中调用了 2 次,而 printmsg
在下面的程序中调用了一次。
我的疑问出现此处:引用
请注意:函数的行为几乎就像外部脚本一样......除了 默认情况下,所有变量在同一个 ksh 之间共享 过程!如果您更改函数内的变量名称...... 离开后变量的值仍然会改变 功能!!
但我们可以在第二个程序的输出中清楚看到i
的值保持不变。但我们确信该函数被调用,因为 print 语句获取了函数的输出并打印了它。 那么为什么两者的输出不同呢?
Here are 2 different versions of a program:
this
Program:
#!/usr/bin/ksh
printmsg() {
i=1
print "hello function :)";
}
i=0;
echo I printed `printmsg`;
printmsg
echo $i
Output:
# ksh e
I printed hello function :)
hello function :)
1
and
Program:
#!/usr/bin/ksh
printmsg() {
i=1
print "hello function :)";
}
i=0;
echo I printed `printmsg`;
echo $i
Output:
# ksh e
I printed hello function :)
0
The only difference between the above 2 programs is that printmsg
is 2times in the above program while printmsg
is called once in the below program.
My Doubt arises here: To quote
Be warned: Functions act almost just like external scripts... except
that by default, all variables are SHARED between the same ksh
process! If you change a variable name inside a function.... that
variable's value will still be changed after you have left the
function!!
But we can clearly see in the 2nd program's output that the value of i
remains unchanged. But we are sure that the function is called as the print statement gets the the output of the function and prints it. So why is the output different in both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您使用反引号(或 $(...))时,您将在子 shell 中执行它。
也就是说,启动一个新的 shell(继承自当前的 shell),然后存在。
编辑:我检查了您的链接,如果您阅读在它的底部,最后一部分,你会看到这个解释。
When you use backticks (or $(...)), you execute it in a subshell.
That is, a new shell is started (which inherits from the current one) and then exists.
Edit: I checked your link, if you read the bottom of it, the very last section, you'll see this explained.