在一個目錄中有帶有空格的檔案和子檔案夾:
$ find ./test
./test
./test/testdir
./test/testdir/file 1 2 3
./test/testdir 2 3 4
./test/testdir 2 3 4/file 5 6 7
./test/testfile
./test/otherdir
./test/otherdir/otherfile
./test/otherfile
$
這只是展示案例的測驗檔案夾示例,但在實際環境中,這是一個巨大的檔案夾,其中包含數百個檔案,大小總計約為 ca。100GB。
我有一個 zip 檔案,其中包含上述檔案夾中某些檔案的更新。在解壓縮更新檔案之前,我想對每個將被此更新替換的檔案進行選擇性備份。
update.zip 檔案中的檔案是:
$ unzip -Z1 update.zip
testdir/
testdir/file 1 2 3
testdir 2 3 4/
testdir 2 3 4/file 5 6 7
testfile
$
Here is the command which I tried to do such backup which failed:
$ tar czvf backup_before_update.tgz -C ./test/ $(unzip -Z1 update.zip|grep -v \/$|sed -r 's/^/"/;s/$/"/'|paste -sd" ")
tar: "testdir/file: Cannot stat: No such file or directory
tar: 1: Cannot stat: No such file or directory
tar: 2: Cannot stat: No such file or directory
tar: 3": Cannot stat: No such file or directory
tar: "testdir: Cannot stat: No such file or directory
tar: 2: Cannot stat: No such file or directory
tar: 3: Cannot stat: No such file or directory
tar: 4/file: Cannot stat: No such file or directory
tar: 5: Cannot stat: No such file or directory
tar: 6: Cannot stat: No such file or directory
tar: 7": Cannot stat: No such file or directory
tar: "testfile": Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
$
當我只執行“echo”并手動運行命令時,沒有這樣的錯誤:
$ echo tar czvf backup_before_update.tgz -C ./test/ $(unzip -Z1 update.zip|grep -v \/$|sed -r 's/^/"/;s/$/"/'|paste -sd" ")
tar czvf backup_before_update.tgz -C ./test/ "testdir/file 1 2 3" "testdir 2 3 4/file 5 6 7" "testfile"
$ tar czvf backup_before_update.tgz -C ./test/ "testdir/file 1 2 3" "testdir 2 3 4/file 5 6 7" "testfile"
testdir/file 1 2 3
testdir 2 3 4/file 5 6 7
testfile
$
我可以使用 eval 并且它也有效:
$ eval $(echo tar czvf backup_before_update.tgz -C ./test/ $(unzip -Z1 update.zip|grep -v \/$|sed -r 's/^/"/;s/$/"/'|paste -sd" "))
testdir/file 1 2 3
testdir 2 3 4/file 5 6 7
testfile
$ eval $(echo tar czvf backup_before_update.tgz -C ./test/ $(unzip -Z1 update.zip|grep -v \/$|sed -r 's/^/"/;s/$/"/'))
testdir/file 1 2 3
testdir 2 3 4/file 5 6 7
testfile
$
即使所有給定的檔案名都在雙引號中,為什么第一個命令會失敗?
uj5u.com熱心網友回復:
當您打開 debug with set -x(并關閉 with set -)時,您將看到結果$(...)被拆分為使用空格作為分隔符的引數。在您的情況下(沒有帶換行符的檔案名),當您創建檔案串列時,您幾乎完成了,每個檔案都在一行上。GNUtar可以使用-T選項從檔案中讀取
-T, --files-from=FILE
Get names to extract or create from FILE.
Unless specified otherwise, the FILE must contain a list of names separated by
ASCII LF (i.e. one name per line). The names read are handled the same way as
command line arguments.
<(cmd)當您希望將結果cmd作為檔案處理時,您可以使用該構造。
tar czvf backup_before_update.tgz -C ./test/ -T <(unzip -Z1 update.zip|grep -v \/$)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397171.html
