Bash 中有效标识符(例如函数、变量等)的规则是什么? [英] What are the rules for valid identifiers (e.g. functions, vars, etc) in Bash?

查看:21
本文介绍了Bash 中有效标识符(例如函数、变量等)的规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 中有效标识符(例如函数、变量等)的规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆