Bash: getopts 中的默认布尔值

Bash: default boolean value in getopts

我想在我的脚本中包含一个默认选项,如果用户使用此选项,请将标志设置为 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

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

#!/bin/bash

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

instructions() {
  echo "Usage: [=10=] [ -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