gpt4 book ai didi

Bash - 用 `set` 恢复位置参数有什么意义?

转载 作者:行者123 更新时间:2023-12-04 15:40:08 26 4
gpt4 key购买 nike

考虑以下解析 bash 脚本参数的代码(比方说 example.sh):

#!/bin/bash
positional=()
while [ $# -gt 0 ]
do
arg="$1"
case ${arg} in
-h|--help|\?) show_usage; exit 0 ;;
-v|--verbose) verbose=1; shift ;;
-f|--file) theFile="$2"; shift; shift;;
*) positional+=("$1"); shift ;;
esac
done
set -- "${positional[@]}"

arg1a="${positional[0]}"; arg1b="$1" # same result, $arg1a == $arg1b
arg2a="${positional[1]}"; arg2b="$2" # same result, $arg2a == $arg2b

通过以下脚本调用:

./example.sh pos1 -v -f toto.txt pos2

  • 在循环之前,"$1"== "pos1""$5"== "pos2"
  • 循环后,set --之前,$1$2$5未定义<
  • 设置--之后,"$1"== "pos1""$2"== "pos2"

而且,在 set -- 之后,${positional[0]} == "pos1"${positional[1]} = = "pos2".

所以,问题是:使用 set -- "${positional[@]}" 的实际意义是什么?

我们确实可以按照提供的相同顺序获取我们的位置参数(使用 ${positional[i]})的值,而无需将其恢复为 $1$2。因此,我不明白使用set -- 的意义。如果我们不在这里使用它,那么 $# -eq 0 就是这样......

请提供一个现实生活中的示例,其中必须使用 set --,即使使用此 ${positional[]} 数组也是如此。

最佳答案

在“while”循环之后,“位置”数组将捕获除“-v”、“--verbose”、“-f”和“--file”之外的所有命令行选项和参数(以及 -f/--file 的参数)。

此时,脚本的其余部分将在没有这些参数的情况下继续运行。

这种编码的可能原因是上面的 block 扩展了脚本的原始行为以包括两个额外的选项(详细和文件),脚本的其他部分不支持这两个选项。

如果脚本将使用用户提供的命令行参数执行另一个不支持详细/文件选项的命令(例如 ls),这将很有用。

# Code to strip verbose/file command line options
while
do
...
done
set --
# Do something above $verbose, $theFile
...
# Original script here - use any unprocessed parameters from command line
ls "$@"

编辑:来自评论:

使用现代 bash,您几乎可以在任何操作中使用数组而不是位置参数。少数异常(exception):内置的:shiftgetopt,仅适用于位置参数

关于Bash - 用 `set` 恢复位置参数有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108699/

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