簡體   English   中英

tar exclude在bash腳本中不起作用

[英]tar exclude is not working inside the bash script

我正在嘗試創建一個文件夾的tar文件,其中有很多文件要排除。 所以我寫了一個腳本( mytar ):

#!/usr/bin/env bash

# more files to be included 
IGN=""
IGN="$IGN --exclude='notme.txt'"

tar --ignore-failed-read $IGN -cvf "$1" "$2"

# following command is working perfectly
# bash -c "tar --ignore-failed-read $IGN -cvf '$1' '$2'"

測試文件夾:

test/
    notme.txt
    test.txt
    test2.txt 

如果執行腳本,它將創建一個tar文件,但不會排除我在IGN列出的文件
顯然,該命令是:

tar --ignore-failed-read --exclude='notme.txt' -cvf test1.tar test  

如果該命令直接在Shell中執行,則該命令運行正常。 我也找到了該腳本的解決方法:在腳本文件中使用bash -c

bash -c "tar --ignore-failed-read $IGN -cvf '$1' '$2'"

我想知道並試圖找出答案,

如果沒有bash -c為什么這個簡單的命令不起作用?
為什么它與bash -c一起使用?

輸出:
第一個輸出不應像稍后那樣容納notme.txt文件
焦油排除流行病

UPDATE 1腳本已更新

這與bash在其shell中擴展變量的方式有關。

設置時:

IGN="--exclude='notme.txt'"

它將擴展為:

tar --ignore-failed-read '--exclude='\''notme.txt'\''' -cvf test1.tar test  

這樣,tar將尋找一個名為\\''notme.txt'\\'' ,但找不到。

您可以使用:

IGN=--exclude='notme.txt'

在shell擴展后,它將被正確解釋,而tar會知道這一點,但我建議您使用變量僅存儲要排除的文件名:

IGN="notme.txt"
tar --exclude="$IGN" -cvf ./test1.tar ./*

在以下命令中,單引號在語法上是(語法上不是單引號,而在文件名參數上不能用引號引起來),以防止shell在包含空格或制表符的情況下拆分參數

tar --ignore-failed-read --exclude='notme.txt' -cvf test1.tar test  

最接近的是使用數組而不是字符串變量:

ign=( --exclude='notme.txt' )
tar --ignore-failed-read "${ign[@]}" -cvf test1.tar test  

暫無
暫無

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

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