gpt4 book ai didi

linux - Sh - 获取下一个数组元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:07 25 4
gpt4 key购买 nike

我的脚本使用的参数是原来的两倍:

第一次使用以下代码,以确保没有我不想要的参数(我只考虑 arg1:arg2:arg3)

     PARAM=$@
while [ "$#" -gt "0" ]; do
case $1 in
arg1)
shift2
;;
arg2)
shift
;;
arg3)
shift
;;
*)
echo "Usage : ./test.sh arg1 <VAL1> <VAL2> [arg2] [arg3]"
exit 2
;;
esac
shift
done

我想重新解析这些参数,并在我得到 arg1 时能够得到以下两个参数,所以我从这样的事情开始:

     for command in $PARAM
do
case $command in
arg1)
shift
VALUE1=$command
shift
VALUE2=$command
exec_arg1
;;
esac
shift

但是在使用“shift”时,我得到错误shift: can't shift the many

shebang 是“#!/bin/sh”,我正在寻找无需使用 bash 的 shebang(即“#!/bin/bash”)的解决方案

最佳答案

您无法将列表连接到字符串并将其安全地转换回列表(没有 complex helper function )。参见 this FAQ .

shift 在不同的 shell 中表现不同。在 Bash 和 Zsh 中,当没有位置参数保留时,shift 只会返回 false。包括 Dash 在内的许多 shell(与 POSIX 相反,可能是因为 ksh 行为)改为抛出 fatal error 。 ksh93 通过内置的 command 提供了解决这个问题的方法,但这似乎也没有被 POSIX 指定,尽管这个 workaroud 无论如何也适用于 Dash,但不是 mksh (有还有我昨天刚刚发现的 mksh 中的一个错误,它阻止了它的工作,维护者可能不会以允许解决方法的方式修复它)。 Busybox 也不遵循 POSIX,也没有给出有意义的退出代码。

无论如何,重点是您不能依赖 shift,因为这里有太多 shell 存在错误。如果可能的话,您应该在不移动参数的情况下迭代参数,并以确保您不会像当前所做的那样移动边缘的方式测试剩余参数的数量。我认为您预验证参数的想法并不比同时验证和解析更好。

#!/bin/sh

f()
if ! ${_called_f+false}; then
while ! ${1+false}; do
case $1 in
arg1)
${3+:} return 1
value1=$2 value2=$3
shift 3
exec_arg1
;;
arg[23])
${2+:} return 1
value1=$1
shift
"exec_arg${value1##"${value1%?}"}" # Only do this crap if restricted to POSIX
;;
*)
return 1
esac
done
else
# Hack nobody will understand since this probably isn't what you want anyway.
_called_f= value1= value2= command eval \
'typeset +x value{1,2} 2>/dev/null; f "$@"'
fi

if ! f "$@"; then
echo 'Error parsing args, exiting...' >&2
exit 1
fi

另请参阅:option parsing

关于linux - Sh - 获取下一个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14200079/

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