bash - 如何将长选项传递给 bash 脚本?

标签 bash shell getopt

./script.sh -abc hello

如何编写我的脚本以使用“-abc”作为选项并将“hello”用作该选项的值?

我应该能够将此值传递给此脚本中的所有函数。假设我有 2 个函数:XY

最佳答案

在你的脚本中使用它:

[[ $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/

相关文章:

c - 整数值和负值的 getopt 错误处理

bash - 使用 awk 比较 2 个不同文件的第一列

linux - 如果 find 不为空,如何显示 true

json - 使用 jq 在 json 中进行类似正则表达式的搜索

git log --before ="4 months"显示 3 周前提交的分支。我究竟做错了什么?

linux - Bash 代码在它应该执行之前执行

c - 为什么 getopt 库中没有 <string.h>?

导入 getopt 时无法调用 Python 模块

bash - 将字符串附加到 bash 数组中的元素,但如果数组为空则不附加字符串

linux - Linux Shell 脚本中复杂的 MongoDB 语法