2014-02-10 24 views
0

我有做while循環,將獲得文件名和運行命令。相當標準的東西。我想要做的排序是文件,我喂到do while循環,然後第一個文件我想運行一個命令1和他們的休息命令2while while循環。讓第一條記錄異常,並像往常一樣繼續循環

find $dir -iname "$search*" |<some commands> | sort -nr 
while read filename; do 
# if its the very 1st file . head - 1 would do that 

echo "command1 > log > 2>&1& " >> appendfile 
echo "if [ $? != 0 ] then ; exit 1 fi " >> appendfile 

# for all other files do this 
echo "command1 > log > 2>&1& " >> appendfile 

現在你明白我在做什麼太。我正在寫些東西給appendfile.ksh,稍後會運行它。我選擇第一個文件大小最小的文件作爲「測試文件」來運行command1。如果作業異常終止該出口否則繼續處理文件的其餘部分 我想辦法如何適應進入該做的第一個文件,而一個稍微特殊處理

回答

1

使用化合物命令分別消耗的第一個文件名,while循環開始之前。這有一個好處,即允許您使用單個重定向將複合命令的所有輸出附加到appendfile,而無需單獨重定向每個echo命令。請務必記下每個命令的更正重定向語法。

find $dir -iname "$search*" |<some commands> | sort -nr | { 
    # This read gets the first line from the pipeline 
    read filename 
    echo "command1 > log 2>&1 " 
    echo "if [ $? != 0 ] then ; exit 1 fi " 

    # These reads will get the remaining lines 
    while read filename; do 
     echo "command2 > log2 2>&1 " 
     echo "if [ $? != 0 ] then ; exit 1 fi " 
    done 
} >> appendfile # If appendfile isn't written to before, you can just use > 

還有一位不請自來的建議:您可以通過

command1 > log 2>&1 || exit 1 

,而不是使用一個明確的if聲明縮短你的腳本。

2

你可以這樣說:

first="" 

while read filename; do 
    if [ -z "$first" ]; then 
    first="$filename" 
    # if its the very 1st file . head - 1 would do that 
    echo "command1 > log > 2>&1& " >> appendfile 
    echo "if [ $? != 0 ] then ; exit 1 fi " >> appendfile 
    else 
    # for all other files do this 
    echo "command2 > log > 2>&1& " >> appendfile 
    fi 
done < <(find "$dir" -iname "$search*" | <some commands> | sort -nr) 
4
#!/bin/bash 
f=1 
find . -name "*.txt" | while IFS= read -r filename 
do 
    if [ $f -eq 1 ]; then 
     echo First file 
    else 
     echo Subsequent file 
    fi 
    ((f++)) 
done 
+0

+1但是'while read filename'應該是'while IFS = read -r filename',除非OP特別要刪除文件名和解釋反斜槓的空格。 –

+1

謝謝你,Ed。我意識到這一點,但集中在「f = 1; if [..];((f ++))」原則上,而不是糾正/批判OP的循環技術。我會更新我的回答,以便「糟糕的例子」消失。再次感謝。 –