天天看點

UNIX/Linux環境程式設計必須需要注意的問題總結

在unix/linux下程式設計必須需要注意一下幾點問題(特别是在運作于windows上的ide或程式設計工具進行開發):

1.大小寫問題。

在檔案或目錄的命名規則中,特别注意駝峰命名法的大小寫區分問題。有些語言的内部變量或者引用方面同樣也是。

2.權限問題。

不要任意操作檔案系統,換句話說,不要動與自己無關的任何檔案(unix/linux下一切都是檔案),特别是新部署或者應用中要生成新檔案時将權限先檢視清楚

3.關于unix檔案編碼問題的再次強調

在運作于windows上的ide或程式設計工具進行開發時特别注意,儲存檔案時一定要将dos檔案格式(file format)轉化成unix檔案格式。

dos檔案格式中換行符為\r\n

unix檔案格式中換行符為\n

現在vim和awk對此有了改進,能自動識别,而grep還不能很好的識别,是以一旦用grep這樣的工具就會導緻出現未知的後果。

附:針對檔案格式做的一些測試:

1

2

3

4

5

6

7

8

9

<code>#!/bin/bash   </code>

<code>#chkconfig: 345 86 14    </code>

<code>#description: startup and shutdown script for chatterserver(port:$serviceport))    </code>

<code>#serviceport=29093    </code>

<code>#serviceport=`grep ^port $(pwd)/../conf/constant.properties | awk -f '=' '{print $2}'`    </code>

<code>portfile=$(</code><code>pwd</code><code>)/..</code><code>/conf/constant</code><code>.properties    </code>

<code>#serviceport=$(cat $portfile | grep ^port | awk -f '=' '{print $2}')    </code>

<code>serviceport=$(</code><code>cat</code> <code>$portfile | dos2unix | </code><code>grep</code> <code>^port)    </code>

<code>echo</code> <code>"success: chatterserver(port:$serviceport) is ok"</code>

上面的constant.properties檔案的fileformat如果為dos,如下圖所示:   

UNIX/Linux環境程式設計必須需要注意的問題總結

則就會出現

UNIX/Linux環境程式設計必須需要注意的問題總結

另一個測試腳本:

10

11

12

<code>cat</code> <code>&gt;.</code><code>/portfile</code><code>&lt;&lt;eof   </code>

<code>port=1080    </code>

<code>eof    </code>

<code>pidfile=.</code><code>/portfile</code>    

<code>cat</code> <code>$pidfile    </code>

<code>#serviceport=$(grep ^port $portfile | awk -f '=' '{print $2}')    </code>

<code>#grep ^port $portfile | awk -f '=' '{print $2}'    </code>

<code># vs    </code>

<code>cat</code> <code>$pidfile | </code><code>grep</code> <code>^port | </code><code>awk</code> <code>-f </code><code>'='</code> <code>'{print $2}'</code>    

<code>serviceport=$(</code><code>cat</code> <code>$pidfile | </code><code>grep</code> <code>^port | </code><code>awk</code> <code>-f </code><code>'='</code> <code>'{print $2}'</code><code>)    </code>

<code>echo</code> <code>$serviceport    </code>

針對上面的檔案格式問題,可以用ide或者檔案編輯器來處理,例如下圖所示的設定:

UNIX/Linux環境程式設計必須需要注意的問題總結
UNIX/Linux環境程式設計必須需要注意的問題總結

也可以用vim中的:set ff=unix轉換,也可以用dos2unix這樣的工具轉換,如下面的腳本所示:

<code># note: $(pwd)/../conf/constant.properties file fileformat must be unix not dos in shell scripts, or will cause some unknown error   </code>

<code># note: grep is vrey sensitive to dos fileformat or unix fileformat    </code>

<code># apt-get install dos2unix    </code>

<code>serviceport=$(</code><code>cat</code> <code>$portfile | dos2unix | </code><code>grep</code> <code>^port | </code><code>awk</code> <code>-f </code><code>'='</code> <code>'{print $2}'</code><code>)</code>

--end--

繼續閱讀