2014-01-23 66 views
1

目錄檢查失敗,我有以下代碼來測試目錄存在:SH:當目錄中存在

PROJECT="somedir" 
if [ -d ~/migrations/$PROJECT ] ; then 
    echo "Test" 
fi 

dst_dir="~/migrations/$PROJECT" 
if [ -d "$dst_dir" ] ; then 
    echo "Test 2" 
fi 

出於某種原因,只輸出測試。我期望它輸出測試測試2

相當新的shell腳本,我錯過了什麼?我覺得它與~有關。

+1

爲了您的方便將來,[shellcheck(http://www.shellcheck.net)會指出,'〜'不加引號擴大。 –

+0

@那個人,謝謝你的資源。 –

+0

顯然在這裏沒有什麼區別,但你應該在單括號內按慣例引用「$ PROJECT」。 – BroSlow

回答

4

因爲代字號~需要在引號外。

嘗試:

dst_dir=~/migrations/$PROJECT 

~報價時不展開。

測試:

s="~" 
ls "$s" 
ls: ~: No such file or directory 

s=~ 
ls "$s" 
# list comes here 
+0

你能否詳細說明一下? –

+0

檢查我更新的答案。 – anubhava

+2

請參閱http://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html – fedorqui

相關問題