sh - /bin/sh Adding an element to the arguments array from within the script
问题描述
Ultimate Goal
Essentially I have a while loop going through each command-line argument passed to the script, but want to set default behaviour if no arguments are passed.
Current solution idea
My plan for this is to test if there are any arguments prior to this while loop and if there aren't any, simply add the default arguments (flags in this case) to the argument array and let the script execute from there as normal.
Problem I'm having
Where I'm tripping up a little here is figuring out the syntax to add these default arguments to the arguments array itself (I can get values from it no problem).
This is what I have so far:
if test $# -eq 0
then
# ADD --default TO ARGUMENTS ARRAY HERE
fi
while test $# -gt 0
do
case "$1" in
--opt1) DO STUFF
;;
--opt2) DO MORE / OTHER STUFF
;;
--default) DO DEFAULT STUFF
;;
esac
shift
done
Following and altering examples using user-defined arrays I have tried:
if test $# -eq 0
then
$+=('--default')
fi
But just get the syntax error
syntax error near unexpected token `'--default''
解决方案
sh
does not have arrays other than the built-in command-line argument list, and thus no +=
operator for arrays.
You also seem to be missing a character; what you wrote evaluates to assigning (default)
to the value of the variable $+
but this variable is not valid (though because there are no arrays, the parentheses cause an error already).
The shell allows you to use set
to manipulate the built-in argument list.
if test $# -eq 0
then
set -- --default
fi
The condition requires the array to be empty, so we simply populate it with the single element you provided; in the general case, you could add stuff to the end with
set -- "$@" --default
or correspondingly to the beginning by putting something before "$@"
(which of course contains the previous value of the argument list).
推荐阅读
- c - 为指向指针数组的指针赋值
- javascript - 如何从浏览器控制台更改 Facebook 帖子文本?
- python - 熊猫根据几列减去数据框中的行
- jmeter - 无需登录多次验证令牌
- javascript - 如何在 HTML 中使用数据属性名称和值 - 略
- javascript - 创建一个带有钳位和焦点的 React CSS 对象
- easyadmin - 如何使用 EasyAdmin 2 和 A2lix TranslationFormBundle 将文本编辑器类型用于翻译类型
- python - 从未等待协程 discord.py
- javascript - 反应原生:swiper,第一次显示时出现问题
- javascript - Bootstrap 5.1.3 导航栏点击后不折叠