问题描述
Bash中标识符(特别是函数名和变量名)的语法规则是什么?
What are the syntax rules for identifiers, especially function and variable names, in Bash?
我编写了一个Bash脚本,并在Ubuntu,Debian,Red Hat 5和6,甚至是旧的Solaris 8盒上的各种版本的Bash上对其进行了测试.脚本运行良好,因此可以运行.
I wrote a Bash script and tested it on various versions of Bash on Ubuntu, Debian, Red Hat 5 and 6, and even an old Solaris 8 box. The script ran well, so it shipped.
但是,当用户在SUSE计算机上尝试使用它时,它给出了无效标识符"错误.幸运的是,我猜测函数名称中包含无效字符是正确的.连字符把它弄乱了.
Yet when a user tried it on SUSE machines, it gave a "not a valid identifier" error. Fortunately, my guess that there was an invalid character in the function name was right. The hyphens were messing it up.
至少在某种程度上经过测试的脚本在另一个Bash或发行版上具有完全不同的行为,这一事实令人不安.如何避免这种情况?
The fact that a script that was at least somewhat tested would have completely different behaviour on another Bash or distro was disconcerting. How can I avoid this?
推荐答案
来自手册:
Shell Function Definitions
...
name () compound-command [redirection]
function name [()] compound-command [redirection]
name
在其他地方定义:
name A word consisting only of alphanumeric characters and under‐
scores, and beginning with an alphabetic character or an under‐
score. Also referred to as an identifier.
因此连字符无效.但是,在我的系统上,它们确实可以工作...
So hyphens are not valid. And yet, on my system, they do work...
$ bash --version
GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)
这篇关于Bash中有效标识符(例如函数,变量等)的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!