bash脚本中没有空间的变量赋值背后的原理是什么 [英] What is the rationale behind variable assignment without space in bash script

查看:62
本文介绍了bash脚本中没有空间的变量赋值背后的原理是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为AWS编写一个自动化流程,该流程需要在bash脚本中进行一些JSON处理和其他操作.我正在关注bash脚本的一些博客,我发现了这一点:

I am trying to write an automate process for AWS that requires some JSON processing and other things in bash script. I am following a few blogs for bash script and I found this:

a=b

,带以下注意事项:

等号(=)的两边都没有空格.我们还可以从变量名的开头删除$符号,当设置

There is no space on either side of the equals ( = ) sign. We also leave off the $ sign from the beginning of the variable name when setting it

这很丑陋,很难读取,并且与其他脚本语言相比也很困难,在编写bash脚本时,用户很容易通过在两者之间留有空格来犯错误.我认为每个人都喜欢编写干净且可读的代码,这种限制肯定不利于代码的可读性.

This is ugly and very difficult to read and comparing to other scripting languages, it is easy for user to make a mistake when writing a bash script by leaving space in between. I think everyone like to write clean and readable code, this restriction for sure is bad for code readability.

你能解释为什么吗?带有示例的解释受到高度赞赏.

Can you explain why? explanation with examples are highly appreciated.

推荐答案

这是因为否则语法会模棱两可.考虑以下命令行:

It's because otherwise the syntax would be ambiguous. Consider this command line:

cat = foo

是对变量 cat 的赋值,还是运行带有参数"="和"foo"的命令 cat ?请注意,"="和"foo"都是完全合法的文件名,因此可以在 cat 上运行.Shell语法通过命令解释来解决此问题,因此要避免这种解释,您需要省略空格. cat = foo 也有同样的问题.

Is that an assignment to the variable cat, or running the command cat with the arguments "=" and "foo"? Note that "=" and "foo" are both perfectly legal filenames, and therefore reasonable things to run cat on. Shell syntax settles this in favor of the command interpretation, so to avoid this interpretation you need to leave out the spaces. cat =foo has the same problem.

另一方面,请考虑:

var= cat

命令 cat 是否在变量 var 设置为空字符串的情况下运行(即 var =''cat 的简写),还是对外壳变量 var 的赋值?同样,shell语法有利于命令解释,因此您需要避免添加空格的诱惑.

Is that the command cat run with the variable var set to the empty string (i.e. a shorthand for var='' cat), or an assignment to the shell variable var? Again, the shell syntax favors the command interpretation so you need to avoid the temptation to add spaces.

shell语法中有很多地方,空格是重要的分隔符.另一个常见的问题是在测试中,如果您忽略以下内容中的任何:

There are many places in shell syntax where spaces are important delimiters. Another commonly-messed-up place is in tests, where if you leave out any of the spaces in:

if [ "$foo" = "$bar" ]

...这将导致不同的含义,这可能会导致错误,或者只是默默地做错了事.

...it will lead to a different meaning, which might cause an error, or might just silently do the wrong thing.

我要说的是shell语法不允许您随意添加或删除空格以提高可读性.甚至不要尝试,您只会破坏事物.

What I'm getting at is that shell syntax does not allow you to arbitrarily add or remove spaces to improve readability. Don't even try, you'll just break things.

这篇关于bash脚本中没有空间的变量赋值背后的原理是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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