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.
 

常用參數

格式::

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

 

Bash代碼  收藏代碼
  1. if [ "today" == "2011-08-29" ]; then  
  2.     :  
  3. else  
  4.     :  
  5. fi  

 

格式:: your comment here

格式:# your comment here

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

 

格式:: 'comment line1

comment line2

more comments'

寫多行註釋。

 

格式:: >file

格式:>file

清空文件file的內容。

 

格式:: ${VAR:=DEFAULT}

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

 

使用示例

示例一 參數擴展

[root@node56 ~]# : abc=1234 
[root@node56 ~]# echo $abc 

[root@node56 ~]# : ${abc:=1234} 
[root@node56 ~]# echo $abc    
1234

[root@node56 ~]# ${abc:=1234} 
-bash: 1234: command not found
[root@node56 ~]#

 

示例二 清空文件

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

 

示例三 腳本註釋、佔位符

腳本test_colon.sh

Bash代碼  收藏代碼
  1. #!/bin/sh  
  2.   
  3. : this is single line comment  
  4.   
  5. : 'this is a multiline comment,  
  6. second line  
  7. end of comments'  
  8.   
  9. if [ "1" == "1" ]; then  
  10.         echo "yes"  
  11. else  
  12.         :  
  13. fi  

 

[root@node56 ~]# ./test_colon.sh 
yes
[root@node56 ~]#


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章