【shell编程】冒号(":")用法

冒号用法

在linux系统中,冒号(:)常用来做路径的分隔符(PATH),数据字段的分隔符(/etc/passwd)等。其实,冒号(:)在Bash中也是一个内建命令,它啥也不做,是个空命令、只起到占一个位置的作用,但有时候确实需要它。当然,它也有它的用途的,否则没必要存在。在·Linux的帮助页中说它除了参数扩展和重定向之外不产生任何作用。

啥也不做,只起到占位符的作用。比如在编写脚本的过程中,某些语法结构需要多个部分组成,但开始阶段并没有想好或完成相应的代码,这时就可以用:来做占位符,否则执行时就会报错。

if [ "today" == "2011-08-29" ]; then  
    :  
else  
    :  
fi  

清空文件内容:

: >file # 方法1
>file   # 方法2

 

注释作用

单行注释:

: your comment here
# your comment here

多行注释:

: 'comment line1
comment line2
more comments'

 

实例:

#!/bin/sh

: this is single line comment

: 'this is a multiline comment,
second line
end of comments'

if [ "1" == "1" ]; then
        echo "yes"
else
        :
fi

输出结果:

[root@node01 demo]# sh test.sh
yes

 

例子:清空文件

[root@node56 ~]# cat <<<"Hello" >123.txt 
[root@node56 ~]# cat 123.txt 
Hello
[root@node56 ~]# : >123.txt 
[root@node56 ~]# cat 123.txt 
[root@node56 ~]#

参考资料

1. shell中冒号 : 用途说明 

posted @ 2022-06-07 21:04  苏格拉底的落泪  阅读(19)  评论(0编辑  收藏  举报