linux - 脚本的输出不是预期的

标签 linux bash

当我使用参数运行此代码时,例如./getopts -a,它会打印“hi -a”,尽管预期的输出将是“hi hello”。有什么想法出了什么问题吗?

 #!/bin/bash

while getopts a:name
do
        case $name in
          a)aopt=$OPTARG;;
          *)echo "Invalid arg";;
        esac
done

if [[ ! -z $aopt ]]; then
    echo $aopt
fi

shift $(($OPTIND - 1))

#exit 0

最佳答案

可能您缺少引号和空格:

    while getopts "a:" name; do
        echo "name=$name";
        case $name in
            a)aopt=$OPTARG;;
            *)echo "Invalid arg";;
        esac
    done
    if [[ ! -z $aopt ]]; then
        echo $aopt
    fi
    shift $(($OPTIND - 1))

通过命令执行:

./myCode“嗨你好”

关于linux - 脚本的输出不是预期的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686040/

相关文章:

bash - 有没有办法编写 ghci session 脚本?

linux - bash,使用此处文档,如何读取多行用户输入,停在空行上

linux - BASH : find fileX[1-20] in directory Y and look if fileX[1-20]. pid 存在

linux - 系统如何监听文件变化?

c - 使用数据包 MMAP 过滤数据包?

bash - 如何使用 awk/bash 脚本减去两列的值并添加到文本文件中的新列

linux - 为 node.js 安装 NPM 时出错

python - 我如何使用 python 读取 linux 程序的输出(顶部)

bash - 在 bash 中使用单个命令为 shell 变量分配默认值

bash - 使用 tput 时如何在 bash 中使用 printf 格式化列