首页 > 系统 > Linux > 正文

Shell 编程:Bash空格的那点事

2019-10-26 18:44:46
字体:
来源:转载
供稿:网友

先了解下bash中什么时候该用空格,什么时候不该用。

1. 等号赋值两边不能有空格
2. 命令与选项之间需要空格
3. 管道两边空格可有可无

我们来看看常见的问题

1. 赋值时等号两边或者只有左边多了空格

igi@gentoo ~ $ var1 = testbash: var1: command not foundigi@gentoo ~ $ echo ${var1:?error}bash: var1: errorigi@gentoo ~ $ echo ${var1?error}bash: var1: errorigi@gentoo ~ $ var2 =testbash: var2: command not foundigi@gentoo ~ $ echo ${var2:?error}bash: var2: errorigi@gentoo ~ $ echo ${var2?error}bash: var2: error

这里我用了bash的变量扩展,${var1:?error}当var1为unset或null(未定义或空)时, 报指定错误; ${var1?error}当var1为unset时,报指定错误 。从执行结果来看,如果等号左边有空格,则变量名当成命令执行,结果报command not found,变量没有被赋值

2. 赋值时等号左边没有空格,右边有空格(这种情况有点特别,你会发现两种情况)

igi@gentoo ~ $ var= testigi@gentoo ~ $ var= nocmdbash: nocmd: command not found

同样是等号右边有空格,第一条命令没报错,而第二条报错了。
这是因为shell中有这么一种执行命令的方式: var=string command
命令command将得到变量var的值(至于在命令执行后,变量var的值是否保留下来,bash4中没有保留,但我在dash中发现时保留下来的,不 同的shell对这个的处理不同), 由于test是个命令,而nocmd不是,所以报了command not found.

igi@gentoo ~ $ var=newtest eval echo /$varnewtestigi@gentoo ~ $ echo $var

注意: 这里我使用了eval, 是想避免在第一次解析时$var被替换成空字符串, 不然就会出现下面的情况(下面是错误的测试方法,在echo还没执行时,$var已经被替换成空字符串)

代码如下:
igi@gentoo ~ $ var=newtest echo $var
igi@gentoo ~ $ echo $var

到这里,相信大家都明白了吧, 对于等号赋值,左右两边不可以有空格,虽然右边有空格不一定报错,但那绝对不是你想要的结果。

3. 命令和选项之间必须有空格
这个似乎大家都明白,为何我还这么罗嗦呢?说到这里,不得不提一下一个非常特别的命令: [ 命令(你没看错,是[ ), 也就是test命令(当然bash中,这是个内置命令,但在这里不影响
我们的理解)。或许你会觉得[命令眼熟,没错,我保证你见过它,来看看下面的例子

igi@gentoo ~ $ if [ "abc" = "abc" ]; then echo ‘they are the same'; fithey are the sameigi@gentoo ~ $ type -a [[ is a shell builtin[ is /usr/bin/[

想起来了吧?[命令经常用到if判断中,当然也有人喜欢这么写

igi@gentoo ~ $ [ "abc" = "cba" ] || echo ‘they are not the same'they are not the sameigi@gentoo ~ $ type -a [[ is a shell builtin[ is /usr/bin/[            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表