Octave的argv解析arguments space-separated,如何传递一个多词argument?
Octave's argv parses arguments space-separated, how to pass a multiple-word argument?
当运行 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 本身确实与第一个调用和其他两个不同。
会在后一种情况下得到两个单词,而在第一个情况下只会得到 '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" other
将 my argument other
打包在一起:
ans =
{
[1,1] = my argument other
}
调用八度脚本时,您应该能够用 ""
包围字符串或用 \
转义空格
./test.m "hello world"
./test.m hello\ world
您遇到的问题是由于您从另一个 bash 脚本和 that bash 调用八度脚本脚本不会将正确转义的字符串转发到八度调用,因为您只是使用 $*
未加引号的字符串。如果你只希望你的八度脚本有一个输入,你会想用 ""
包围 $*
#!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
}
更新
正如 所指出的那样,如果要存储输入,则需要将它们存储在数组中
a=("$@")
./test.m "${a[@]}"
当运行 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 本身确实与第一个调用和其他两个不同。 会在后一种情况下得到两个单词,而在第一个情况下只会得到 '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" other
将 my argument other
打包在一起:
ans =
{
[1,1] = my argument other
}
调用八度脚本时,您应该能够用 ""
包围字符串或用 \
转义空格
./test.m "hello world"
./test.m hello\ world
您遇到的问题是由于您从另一个 bash 脚本和 that bash 调用八度脚本脚本不会将正确转义的字符串转发到八度调用,因为您只是使用 $*
未加引号的字符串。如果你只希望你的八度脚本有一个输入,你会想用 ""
$*
#!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
}
更新
正如
a=("$@")
./test.m "${a[@]}"