./script.sh -abc hello
如何编写我的脚本以使用“-abc”作为选项并将“hello”用作该选项的值?
我应该能够将此值传递给此脚本中的所有函数。假设我有 2 个函数:X
和 Y
。
最佳答案
在你的脚本中使用它:
[[ $1 == -abc ]] && value="$2" || echo invalid option
如果您不想在错误的选项或没有选项时打印任何消息,则省略 || echo ...
部分,value
将为空。
如果你想让第二个参数成为必须,那么:
[[ $1 == -abc ]] && [[ $2 != "" ]] && value="$2" || echo invalid option
使用 if else 循环会让你完全控制这个:
if [[ $1 == -abc ]]; then
#if first option is valid then do something here
if [[ $2 != "" ]]; then
value="$2"
else
#if second option is not given then do something here
echo invalid option
fi
else
echo invalid option
#if first option is invalid then do something here
fi
如果你想让第一个参数也成为必须的,那么将第一个 if 语句行更改为
if [[ $1 == -abc && $1 != "" ]]; then
If you want to pass as many arguments as you wish and process them, then use something like this:
#!/bin/bash
opts=( "$@" )
#if no argument is passed this for loop will be skipped
for ((i=0;i<$#;i++));do
case "${opts[$i]}" in
-abc)
# "${opts[$((i+1))]}" is the immediately follwing option
[[ "${opts[$((i+1))]}" != "" ]] &&
value="${opts[$((i+1))]}"
echo "$value"
((i++))
#skips the nex adjacent argument as it is already taken
;;
-h)
#dummy help option
echo "Options are [-abc value], -h"
;;
*)
#other unknown options
echo invalid option
break
;;
esac
done
这是一个处理多个参数的例子,只有两个选项可用 -abc value
和 -h
关于bash - 如何将长选项传递给 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29955757/