簡體   English   中英

無法在 bash 腳本中的文件名中使用空格 tar 文件數組

[英]Cannot tar array of files with spaces inside filename inside bash script

我有 bash 腳本my_tar.sh ,它在 3 個文件上調用tar czf output.tgz ,文件名空間從數組傳遞: filefile 2file 3

#!/bin/bash

declare -a files_to_zip

files_to_zip+=(\'file\')
files_to_zip+=(\'file 2\')
files_to_zip+=(\'file 3\')

echo "tar czf output.tgz "${files_to_zip[*]}""
tar czf output.tgz "${files_to_zip[*]}" || echo "ERROR"

雖然存在三個文件,但在腳本中運行tar時,它以錯誤結束。 但是,當我在 bash 控制台中運行echo輸出(與my_tar.sh下一個命令相同)時, tar運行正常:

$ ls
file  file 2  file 3  my_tar.sh
$ ./my_tar.sh
tar czf output.tgz 'file' 'file 2' 'file 3'
tar: 'file' 'file 2' 'file 3': Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors
ERROR
$ tar czf output.tgz 'file' 'file 2' 'file 3'
$ 

有任何想法嗎?

問題是,您對'轉義,從而將其添加到文件名中,而不是使用它來引用字符串:

files_to_zip+=(\'file 2\')

對比

files_to_zip+=( 'file 2' )

此外,通常建議使用@而不是星號 ( * ) 來引用所有數組元素,因為在引用 (-> http://tldp.org/LDP/abs/html/arrays. html ,示例 27-7) 。

此外,我還假設您的意圖是在打印出數組元素時在字符串中加上引號。 為此,您需要對引號進行轉義。

echo "tar czf output.tgz \"${files_to_zip[@]}\""

你的固定腳本看起來像

#!/bin/bash

declare -a files_to_zip

files_to_zip+=( 'file' )
files_to_zip+=( 'file 2' )
files_to_zip+=( 'file 3' )

echo "tar czf output.tgz \"${files_to_zip[@]}\""
tar czf output.tgz "${files_to_zip[@]}" || echo "ERROR"

暫無
暫無

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

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