天天看點

我使用過的Linux指令之:(冒号) - 啥也不做(除了……)我使用過的Linux指令之:(冒号) - 啥也不做(除了……)

我使用過的Linux指令之:(冒号) - 啥也不做(除了……)

本文連結:http://codingstandards.iteye.com/blog/1160298   (轉載請注明出處)

用途說明

我們知道,在Linux系統中,冒号(:)常用來做路徑的分隔符(PATH),資料字段的分隔符(/etc/passwd)等。其實,冒号(:)在Bash中也是一個内建指令,它啥也不做,是個空指令、隻起到占一個位置的作用,但有時候确實需要它。當然,它也有它的用途的,否則沒必要存在。在·Linux的幫助頁中說它除了參數擴充和重定向之外不産生任何作用。

man : 寫道 : [arguments]

    No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.  

常用參數

格式::

·啥也不做,隻起到占位符的作用。比如在編寫腳本的過程中,某些文法結構需要多個部分組成,但開始階段并沒有想好或完成相應的代碼,這時就可以用:來做占位符,否則執行時就會報錯。

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

格式:: your comment here

格式:# your comment here

寫代碼注釋(單行注釋)。

格式:: 'comment line1

comment line2

more comments'

寫多行注釋。

格式:: >file

格式:>file

清空檔案file的内容。

格式:: ${VAR:=DEFAULT}

當變量VAR沒有聲明或者為NULL時,将VAR設定為預設值DEFAULT。如果不在前面加上:指令,那麼就會把${VAR:=DEFAULT}本身當做一個指令來執行,報錯是肯定的。

使用示例

示例一 參數擴充

[[email protected] ~]# : abc=1234

[[email protected] ~]# echo $abc

[[email protected] ~]# : ${abc:=1234}

[[email protected] ~]# echo $abc   

1234

[[email protected] ~]# ${abc:=1234}

-bash: 1234: command not found

[[email protected] ~]#

示例二 清空檔案

[[email protected] ~]# cat <<<"Hello" >123.txt

[[email protected] ~]# cat 123.txt

Hello

[[email protected] ~]# : >123.txt

[[email protected] ~]# cat 123.txt

[[email protected] ~]#

示例三 腳本注釋、占位符

腳本test_colon.sh

#!/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      

[[email protected] ~]# ./test_colon.sh

yes

[[email protected] ~]#

問題思考

相關資料

【1】Kpld’s Blog  Kpld’s Blog

http://kpld8888.wordpress.com/

【2】nighteblis.cublog.cn  bash中的冒号, 以及bash bomb解析還有各種各樣的炸*彈

http://www.cublog.cn/u1/40976/showart_2528550.html

【3】清水如畫的部落格  2011-03-20 bash之特殊符号冒号、大括号擴充應用、代碼塊

http://blog.sina.com.cn/s/blog_4002e0d20100qh4w.html

傳回 我使用過的Linux指令系列總目錄

繼續閱讀