首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >printf无效选项- 'd‘

问printf无效选项- 'd‘
EN

Unix & Linux用户
提问于 2021-07-22 12:13:12
回答 1查看 1.1K关注 0票数 -1

我正在执行printf '%s\n' "$@",并使用

代码语言:javascript
复制
pfm "-d DIR" "--directory=DIR"

我会犯错误,即:

代码语言:javascript
复制
bash: invalid option -- 'd'
bash: invalid option -- ' '
bash: invalid option -- 'D'
bash: invalid option -- 'I'
bash: invalid option -- 'R'
bash: unrecognized option '--directory=DIR'

这是相关代码

代码语言:javascript
复制
printfm ()
{
  # Process command line options
  shortopts="hVw::"
  longopts="help,version,warning:"

  opts=$(getopt -o "$shortopts" -l "$longopts"  \
        -n "$(basename $0)" -- "$@")
  if [ $? -eq 0 ]; then
    eval "set -- ${opts}"
    while [ $# -gt 0 ]; do
      case "$1" in
        -V|version)
          printf "V01 Jul 2021 Wk27"
          printf ""
          ;;
        -h|-\?|--help)
          help=1
          printf "Prints two text strings on two lines.\n"
          printf "\$@ TEXT  Sentences to print en new lines.\n"
          shift
      local -r f=0
      break
      ;;
          # ......................................................
        -w|--warning)
      case "$2" in
             "1") local -r warn="first";  shift 2  ;;
             *)   local -r warn="all";    shift 2  ;;
          esac
      local -r f=1
      ;;
        --)
          shift;  break  ;;
      esac
    done
  else
    shorthelp=1 # getopt returned (and reported) an error.
  fi

  red=$(tput setaf 9)  
  rgl=$(tput sgr0)

  local f=1
  if (( f == 1 )); then

    # print normal multi-line text
    [[ ! -z warn ]] && printf '%s\n' "$@"

    # print multi-line warnings
    if [[ -n warn && "$warn" == "first" ]]; then
      printf '%s\n' ${red}"$1"${rgl}  # first line red
      printf '%s\n' "${@:2}"          # remaining, uncoloured
    elif [[ -n warn && "$warn" == "all" ]]; then
      printf '%s\n' ${red}"$@"${rgl}  # all lines red
    fi

  fi
  return 0
}

alias pfm=printfm 
EN

回答 1

Unix & Linux用户

回答已采纳

发布于 2021-07-22 15:00:43

这里没有涉及printf的问题。

您的printfm函数接受参数并执行自己的选项解析。它采用的选项是-V、-h、-?、-w、--warning和--help (请注意,在case语句中,--version将被识别,但不能对其进行操作,因为在version前面有一个错误,一个缺失的-- )。当您使用两个参数-d DIR和--directory=DIR调用它时,getopt实用程序会抱怨字符串包含未知的选项。

将类似于选项的非选项参数传递给实用程序或函数的常见方法是使用-- (“双破折号”)从非选项参数中分隔实际选项:

代码语言:javascript
复制
printfm -- "-d DIR" "--directory=DIR"

这由您的printfm代码正确地处理,将导致选项解析在--处停止,并允许您以非选项参数的形式接收这两个字符串,即使它们以破折号开头。

相关信息:

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

https://unix.stackexchange.com/questions/659458

复制
相关文章

相似问题

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