提取“$@"中最后一个参数之前的参数 [英] Extract parameters before last parameter in "$@"
问题描述
我正在尝试创建一个 Bash 脚本,该脚本将从命令行给出的最后一个参数提取到一个变量中,以便在其他地方使用.这是我正在处理的脚本:
I'm trying to create a Bash script that will extract the last parameter given from the command line into a variable to be used elsewhere. Here's the script I'm working on:
#!/bin/bash
# compact - archive and compact file/folder(s)
eval LAST=$$#
FILES="$@"
NAME=$LAST
# Usage - display usage if no parameters are given
if [[ -z $NAME ]]; then
echo "compact <file> <folder>... <compressed-name>.tar.gz"
exit
fi
# Check if an archive name has been given
if [[ -f $NAME ]]; then
echo "File exists or you forgot to enter a filename. Exiting."
exit
fi
tar -czvpf "$NAME".tar.gz $FILES
由于第一个参数可以是任意数量,我必须找到一种方法来提取最后一个参数,(例如压缩文件.a文件.b文件.d文件-a-b-d.tar.gz).现在,存档名称将包含在要压缩的文件中.有没有办法做到这一点?
Since the first parameters could be of any number, I have to find a way to extract the last parameter, (e.g. compact file.a file.b file.d files-a-b-d.tar.gz). As it is now the archive name will be included in the files to compact. Is there a way to do this?
推荐答案
要从数组中删除最后一项,您可以使用以下方法:
To remove the last item from the array you could use something like this:
#!/bin/bash
length=$(($#-1))
array=${@:1:$length}
echo $array
更短的方式:
array=${@:1:$#-1}
但是 arays 是一种Bashism,尽量避免使用它们:(.
But arays are a Bashism, try avoid using them :(.
这篇关于提取“$@"中最后一个参数之前的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!