首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Bash: getopts中的默认布尔值

Bash: getopts中的默认布尔值
EN

Stack Overflow用户
提问于 2019-06-12 09:29:12
回答 1查看 1.6K关注 0票数 2

我希望在我的脚本中包含一个默认选项,如果用户使用此选项,请将标志设置为true或默认设置为false。脚本似乎没有接受false或true作为布尔值。我怎样才能使它成为布尔型呢?

代码语言:javascript
运行
复制
flag=

instructions() {
  echo " -a File name" >&2
  echo " -f optional boolean" flag=${flag:-false}
}

while getopts ":a:fi" option; do
  case "$option" in
    a ) file=$OPTARG;;
    f ) flag=true;;
    u )  
       instructions
       ;;
    \?)
      echo "Not valid -$OPTARG" >&2
      instructions
      ;;
    : ) echo "args required";;
  esac
done

if [[ "$flag" != true || "$flag" != false ]]; then
  echo "Not a boolean value"
fi
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-12 14:56:50

检查这一点,我对你的脚本做了一些修复(在代码中注释)以及一个适当的格式。

代码语言:javascript
运行
复制
#!/bin/bash

# Set the default value of the flag variable
flag=false

instructions() {
  echo "Usage: $0 [ -a FILE ] [ -f ]" >&2
  echo " -a File name" >&2
  echo " -f optional boolean flag=${flag:-false}" >&2
}


# If the script must be executed with options, this checks if the number of arguments
# provided to the script is greater than 0
if [ $# -eq 0 ]; then
    instructions
    exit 1
fi

while getopts ":a:fi" option; do
  case "${option}" in
    a ) 
       file="$OPTARG"
       ;;
    f ) 
       flag=true
       ;;
    i ) # "u" is not a valid option
       instructions
       exit 0
       ;;
    \?)
       echo "Option '-$OPTARG' is not a valid option." >&2
       instructions
       exit 1
       ;;
    : )
       echo "Option '-$OPTARG' needs an argument." >&2
       instructions
       exit 1
       ;;
  esac
done

# Since a variable can't have 2 values assigned at the same time, 
# you should use && (and) instead of || (or)
if [[ "$flag" != true ]] && [[ "$flag" != false ]]; then
  echo "Not a boolean value"
fi

exit 0
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56553525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档