繁体   English   中英

如何传递具有多个参数的变量以一次全部起作用?

[英]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=("$@")
...

https://ss64.com/bash/shift.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM