2014-03-24 40 views
3

我想檢查一個目錄是否存在並且它有訪問權限;如果是,則執行任務。這是我寫的代碼,可能沒有正確的語法。檢查一個目錄是否存在並且可訪問

你能幫我改正嗎?

dir_test=/data/abc/xyz 
if (test -d $dir_test & test –x $dir_test -eq 0); 
then 
cd $dir_test 
fi 

我相信這也可以這樣寫。

dir_test=/data/abc/xyz 
test -d $dir_test 
if [ $? -eq 0 ]; 
then 
test –x $dir_test 
if [ $? -eq 0 ]; 
then 
cd $dir_test 
fi 
fi 

我們該如何更有效地編寫這些內容?

+0

因爲'''''''''是'test'的同義詞,所以將其歸類爲**無用的'test' ** ;-)請參閱@chepner以獲得解釋。 –

+0

更多的例子和解釋在這裏:[如何檢查一個目錄是否存在於一個shell腳本](http://stackoverflow.com/questions/59838/how-to-check-if-a-directory-exists-in-a -shell-script) –

回答

10

寫原test爲基礎的解決方案將是

if test -d "$dir_test" && test –x "$dir_test"; 
then 
    cd $dir_test 
fi 

但如果測試失敗,你變化目錄你會怎麼做的最好的方法是什麼?腳本的其餘部分可能無法按預期工作。

您可以通過使用[代名詞test縮短這個:

if [ -d "$dir_test" ] && [ -x "$dir_test" ]; then 

,或者您可以使用bash提供的條件命令:

if [[ -d "$dir_test" && -x "$dir_test" ]]; then 

最好的解決辦法,因爲你要如果測試成功,更改目錄是簡單地嘗試它,如果失敗則中止:

cd "$dir_test" || { 
    # Take the appropriate action; one option is to just exit with 
    # an error. 
    exit 1 
} 
+0

只有部分我不明白的是,如果我使用聲明cd「$ dir_test || {exit1}」它會評估目錄是否存在並可訪問? –

+0

如果'cd'成功,則不評估「||」。 – chepner

+0

明白了非常感謝 –

0
if [ -d $dir_test -a -x $dir_test ] 

相反,如果你有在/ usr/bin中/ CD:

if [ /usr/bin/cd $dir_test ] 
+1

POSIX標準建議'[-d $ dir_test] && [-x $ dir_test]'代替'-a'運算符。 – chepner

1
dir_test=/data/abc/xyz 
if (test -d $dir_test & test –x $dir_test -eq 0); # This is wrong. The `-eq 0` part will result in `test: too many arguments`. The subshell (parens) is also unnecessary and expensive. 
then 
cd $dir_test 
fi 

cd可以告訴你,如果一個目錄可訪問。只要做到

cd "$dir_test" || exit 1; 

即使你決定使用test第一,出於某種原因,你應該仍然檢查cd退出狀態,以免你有一個競爭條件。

相關問題