2013-07-02 94 views
0

我有一個名爲bundle的腳本,它使用Here-documents將文本文件合併到一個文件中。這些文件的名稱在調用bundle腳本時作爲參數傳遞,放在一個單獨的文件(這裏稱爲filebundle)中,這個文件然後可以作爲bash腳本執行,以便將這些文件分解成單獨的文件。Bash:搜索一個命令塊的腳本,然後執行這些命令

這裏是束腳本:

#! /bin/bash 
# bundle: group files into distribution package. 

echo "# To unbundle, bash this file." 

for i 
do 
    echo "echo $i 1>&2" 
    echo "cat >$i <<'End of $i'" 
    cat $i 
    echo "End of $i" 
done 

此,當執行如下

$ bash bundle file1.txt file2.txt > filebundle 

結果在下面的文件,命名爲filebundle:

# To unbundle, bash this file. 
echo file1.txt 1>&2 
cat >file1.txt <<'End of file1.txt' 
This is file1. 
End of file1.txt 
echo file2.txt 1>&2 
cat >file2.txt <<'End of file2.txt' 
This is file2. 
End of file2.txt 

,正如我說,可以bashed解包file1.txt和file2.txt

我的問題如下:我必須重新編寫捆綁腳本,以便可以使用或不使用文件名作爲參數來執行由它產生的filebundle文件,並且可以相應地解包其中包含的文件。

例如:

$ bash filebundle file2.txt 

將分拆僅FILE2.TXT而不是FILE1.TXT。另外,沒有參數的bashing filebundle會解包filebundle中的所有文件。

我想我應該用「如果......那麼......否則」控制結構根據傳遞的參數解包文件,而我只能想到用一些像

for i in [email protected]; do 
    grep "$i" <<'End of $i' | bash 
done 

找到filebundle內的特定文件並解壓縮它們。然而,我似乎無法將它們放在一起工作。

您的想法和建議非常感謝。

回答

0

當您解包時,您不必查找特定文件。 if..then負責照顧。

使文件包是這樣的一組塊的:

if [[ $# = 0 ]] || contains "file1.txt" "[email protected]" 
then 
cat > file1.txt << 'End of file1.txt' 
DATA HERE 
End of file1.txt 
fi 

其中contains是檢查對於所述第一元件之間的其餘部分的功能,例如

contains() { 
    var=$1 
    shift 
    for f 
    do 
     [[ $var = "$f" ]] && return 0 
    done 
    return 1 
} 

如果沒有參數,或者文件名在其中,那麼每個文件將只被解綁。

在開始運行這些塊之前,可以在頭文件中添加額外的邏輯以確保文件中存在指定的所有文件名。

+0

這工作完美。謝謝。 – jvasilakes