【问题标题】:Octave's argv parses arguments space-separated, how to pass a multiple-word argument?Octave 的 argv 以空格分隔解析参数,如何传递多字参数?
【发布时间】:2016-11-01 07:05:22
【问题描述】:

运行test.sh bash 脚本时

#!/bin/bash +x

./test.m $*

以下列方式之一调用test.m GNU Octave 可执行脚本:

./test.sh my argument
./test.sh "my argument"
./test.sh 'my argument'

argv() 将始终解析这两个字符串:

ans = 
{
  [1,1] = my
  [2,1] = argument
}

有没有办法在一个参数中同时获取两个单词,而不需要进一步处理结果?或者换一种说法,分隔符可以和空格不一样吗?

有趣的是,bash 本身确实与第一个调用和其他两个调用有所不同。 $1 在后一种情况下会同时得到两个词,而在第一个中只会得到 'my'。

其次,如果参数在发送到 Octave 脚本之前存储在变量中会怎样:

#!/bin/bash +x

a="$@"

./test.m $a

这将给出相同的结果,两个词:

ans = 
{
  [1,1] = my
  [2,1] = argument
}

使用./test.m "$a"

#!/bin/bash +x

a="$@"

./test.m "$a"

将具有传递单个字符串的效果,包括所有参数:./test.sh "my argument" othermy argument other 打包在一起:

ans = 
{
  [1,1] = my argument other
}

【问题讨论】:

  • @Suever 抱歉,已更新!

标签: bash parsing octave argv


【解决方案1】:

在调用 octave 脚本时,您应该能够使用 "" 包围字符串或使用 \ 转义空格

./test.m "hello world"
./test.m hello\ world

您遇到的问题是由于您正在从另一个 bash 脚本中调用您的 octave 脚本,并且 那个 bash 脚本没有将您正确转义的字符串转发到八度调用,因为您只是使用未引用的$*。如果您只希望您的 octave 脚本有一个输入,您需要用 "" 包围 $*

#!bin/bash
./test.m "$*"

然后调用它:

./test.sh "hello world"

{
  [1,1] = hello world
}

然而,更强大的选项是使用"$@",它将适当地转发所有输入并允许您传递多个多字参数

#!/bin/bash
./test.m "$@"

并使用它

./test.sh "hello world" "how are you"

{
  [1,1] = hello world
  [2,1] = how are you
}

更新

正如@Benjamin 所指出的,如果你想存储输入,你需要将它们存储在一个数组中

a=("$@")
./test.m "${a[@]}"   

【讨论】:

  • "$@" 确实成功了。但是现在,如果在实际调用 Octave 脚本之前将参数存储在变量中会怎么样(问题已更新)。
  • @nightcod3r 您的更新并不清楚您正在尝试做什么以及为什么。你能显示实际的代码吗?可能有更好的方法。
  • @nightcod3r 您必须将它们分配给一个数组:a=("$@"),然后将它们与 "${a[@]}" 一起使用。
猜你喜欢
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 2017-03-21
  • 2020-09-14
  • 2017-01-25
  • 2012-09-23
  • 2016-03-13
  • 2012-04-25
相关资源
最近更新 更多