【问题标题】:Bash: default boolean value in getoptsBash:getopts 中的默认布尔值
【发布时间】:2019-06-12 01:29:11
【问题描述】:

我想在我的脚本中包含一个默认选项,如果用户使用此选项,请将标志设置为 true,否则默认情况下应该为 false。脚本似乎不接受 false 或 true 作为布尔值。我怎样才能使它成为布尔值?

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

【问题讨论】:

  • 请考虑首先通过shellcheck 运行您的脚本,以解决所有机器可检测到的问题,例如为什么您的脚本总是打印“不是布尔值”。如果仍有问题,请编辑和更新
  • @Pluto : 你是如何调用这个脚本的?
  • @Pluto : flag总是不同于 truefalse
  • 我刚刚注意到您没有标记答案,您是否遇到过任何问题?如果是这样,请告诉我,我会尽力帮助您解决问题。

标签: bash shell scripting getopts


【解决方案1】:

检查一下,我对您的脚本进行了一些修复(在代码中注释)以及正确的格式。

#!/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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 2014-02-25
    • 2015-01-11
    • 2020-05-21
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多