簡體   English   中英

為什么此Shell腳本不起作用?

[英]Why does this shell script not work?

我注意到find -execdir不是可移植的,因此我決定找到一種僅使用find -exec來實現相同效果的可移植方式。 為此,必須能夠確定'find'從'/'指向目錄的路徑是否包含任何符號鏈接,如果存在,則拒絕遍歷該符號鏈接。 我寫了一個小腳本來確定給定的路徑是否包含符號鏈接,但是無論我給出什么,它似乎總是返回代碼1。 沒有命令輸出任何東西,除非我給它提供了一個非目錄,在這種情況下,第一個printf命令被觸發。

#!/bin/sh -e
# If any commands fail, the script should return a nonzero status
[ -d "$1" ] || printf "%s is not a directory" "$1" && exit 1  # Tests if argument is a directory
cd "$1" || echo "Could not change directory" && exit 1 # If it is a directory, goes to it
until [ "$PWD" = '/' ] # Loop until root directory reached 
do
    cd .. || echo "Could not change directory" && exit 1 # Go to parent directory
    [ -d "$PWD" ] || printf "%s is not directory" "$PWD" && exit 1 # Check that this is a directory
done
echo "Given an okay directory"
exit 0

用bash(與類似c的語言不同) &&|| 具有相同的優先級。 那意味着你

command || echo error && exit 1

語句被解釋為

{ command || echo error } && exit 1

因為即使command不執行, echo也很可能成功,所以第一個塊將成功執行,並且exit語句將被執行。

對於每個條件行,都應將失敗包含在() 例如:

[ -d "$1" ] || (printf "%s is not a directory" "$1" && exit 2)

我將進一步說明@Kevin編寫的內容:如果第一條語句失敗( [ -d ] ),則第二條語句將執行。 由於第二個成功(僅在極少數情況下printf失敗),因此將執行最后一條語句。 以這種格式,只有前兩個都失敗,才不會執行exit語句。 如果它不是目錄,您將獲得一個printf和一個出口。 如果是目錄,則第一個|| 變為true,bash不再費心測試下一個(printf),而是再次轉到&& ,即出口。 將故障封閉為一個將防止這種情況。

您可以檢查$1是否不是帶有相反的目錄! -d ! -d並使用if; then if; then在返回true后執行命令。

#!/bin/sh -e
# If any commands fail, the script should return a nonzero status
if [ ! -d "$1" ]
then
    printf "%s is not a directory" "$1"
    exit 1 # Tests if argument is a directory
fi
cd "$1" # If it is a directory, goes to it
until [ "$PWD" = '/' ] # Loop until root directory reached
do
    cd .. # Go to parent directory
done
echo "Given an okay directory"
exit 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM