gpt4 book ai didi

bash - 提取 "$@"中最后一个参数之前的参数

转载 作者:行者123 更新时间:2023-11-29 08:40:08 25 4
gpt4 key购买 nike

我正在尝试创建一个 Bash 脚本,该脚本将从命令行给出的最后一个参数提取到一个变量中以供其他地方使用。这是我正在处理的脚本:

#!/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

由于第一个参数可以是任意数字,我必须找到一种方法来提取最后一个参数(例如 compact file.a file.b file.d files-a-b-d.tar.gz)。现在,存档名称将包含在要压缩的文件中。有办法做到这一点吗?

最佳答案

要从数组中删除最后一项,您可以使用如下方法:

#!/bin/bash

length=$(($#-1))
array=${@:1:$length}
echo $array

更短的方式:

array=${@:1:$#-1}

但是数组是一个 Bashism , 尽量避免使用它们:(。

关于bash - 提取 "$@"中最后一个参数之前的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1215538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com