【问题标题】:How to get all input inside quote into variable如何将引号内的所有输入转换为变量
【发布时间】:2019-06-20 14:26:50
【问题描述】:

我想将我在" 中发送的任何内容插入到变量中。

例如:

check.sh:

#!/bin/bash
./b.sh -a "$@"

b.sh:

#!/bin/bash

while getopts ":a:b:c:" opt; do
  case ${opt} in
        a) A="$OPTARG"
;;
        b) B="$OPTARG"
;;
        c) C="$OPTARG"
;;
        :) echo "bla"
exit 1
;;
esac
done

echo "a: $A, b: $B, c: $C"

运行#1: 期望的结果:

user@host $  ./check.sh -a asd -b "asd|asd -x y" -c asd
a: -a asd -b "asd|asd -x y" -c asd, b: ,c: 

实际结果:

user@host $  ./check.sh -a asd -b "asd|asd -x y" -c asd
a: -a, b: , c:

运行#2: 期望的结果:

user@host $ ./check_params.sh -a asd -b asd|asd -c asd
a: -a asd -b asd|asd -c asd, b: ,c:

实际结果:

user@host $ ./check_params.sh -a asd -b asd|asd -c asd
-bash: asd: command not found

【问题讨论】:

  • check.sh 在它获得的 arg 列表之前添加了 -a,因此它有效地运行了 ./b.sh -a -a asd -b "asd|asd -x y" -c asd -- 加倍的 -a 引起了很多混乱。

标签: string bash getopts


【解决方案1】:

使用$* 代替$@

check.sh:

#!/bin/bash
./b.sh -a "$*"

"$*" 是与$IFS 变量连接在一起的所有位置参数的字符串表示形式。而$@ 扩展为单独的参数。

另请注意,在您的第二个示例中,您需要使用引号管道字符串:

./check.sh -a asd -b 'asd|asd' -c asd

Check: What is the difference between “$@” and “$*” in Bash?

【讨论】:

  • 如果我也需要' 被转发怎么办?
  • 例如./check.sh -a asd -b 'asd asd' -c asd 的输出应该是:a: -a asd -b 'asd asd' -c asd, b: ,c:
  • 你应该引用它:./check.sh "-a asd -b 'asd asd' -c asd"
  • 我不能。 check.sh 实际上代表了许多不同的脚本,它们有时会调用其他通用脚本b.sh
  • @Nir 你可能想从阅读Bash FAQ 050开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2020-02-02
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 2016-01-01
相关资源
最近更新 更多