![](/img/trans.png)
[英]In C, how to pass a variable number of arguments (say, 50+) to a function which va_start() understands prior to calling vsnprintf()?
[英]How to pass a variable which has multiple arguments to function all at once?
我正在嘗試創建一個命令,該命令允許用戶輸入名稱作為要創建的壓縮文件(將成為tar.gz文件)的第一個參數,並將文件名和目錄名作為第二個參數。
到目前為止,我有這個腳本
name_of_archive=$1
directory_or_file_paths=$2
if [ $# -eq 0 ]
then
echo "Usage: $0 [name of archive you wish to create] [path of directories or files you wish to compress]"
echo "You must enter atleast one file or directory name"
exit 1
else
if [ -e "$directory_or_file_paths" ] || [ -d "$directory_or_file_paths" ]
then
tar -czvf "$name_of_archive".tar.gz "$directory_or_file_paths"
echo "The filenames or directories you specified have been compressed into an archive called $name_of_archive.tar.gz"
else
echo "Some or all of the file or directory names you have given do not exist"
fi
exit
fi
這是我使用命令時得到的:
compression2.bash compression1 ./test ./listwaste
./test/
./test/test2/
./test/test2/2
./test/1
The filenames or directories you specified have been compressed into an archive called compression1.tar.gz
第一個是目錄,第二個是文件。 如果我嘗試分別壓縮兩個文件,則可以使用它,但是一次嘗試壓縮多個文件或目錄或混合文件時,則無法使用。 我希望它能夠做到這一點。
將文件名存儲在字符串中不是一個好主意。 將它們存儲在數組中是一種更好的方法:
#!/usr/bin/env bash
[[ $# -lt 2 ]] && exit 1
name=$1; shift
files=("$@")
#exclude all files/directories that are not readable
for index in "${!files[@]}"; do
[[ -r ${files[index]} ]] || unset "files[index]"
done
[[ ${#files[@]} -eq 0 ]] && exit 1
if tar -czvf "${name:-def_$$}.tar.gz" "${files[@]}"; then
echo "Ok"
else
echo "Error"
exit 1
fi
shift; files=("$@")
shift; files=("$@")
丟棄第一個參數(名稱),並將其余參數(文件名)保存到數組中。
您還可以使用更直接的方法為tar
構建文件名數組:
name=$1; shift
for file; do
[[ -r $file ]] && files+=("$file")
done
那是因為您只查看第二個參數,並將其放在directory_or_file_paths變量中。 每當Linux在命令中找到空格時,它將其視為另一個參數,因此您甚至都不會查看這些其他文件或文件夾。 您需要做的是,如果參數的數量不為0,並且您將第一個作為您的name_of_archive,那么您將需要遍歷所有其余參數並構造一個包含所有參數的字符串,並用空格分隔這就是您將為tar命令提供的參數。
我想在將第一個輸入輸入到存檔的變量名之后,您想使用shift。 然后,您可以傳遞整個列表,而不是僅傳遞存檔的一個參數。
name_of_archive=$1
shift
directory_or_file_paths=("$@")
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.