Arrays 命令行中的Shell脚本数组

Arrays 命令行中的Shell脚本数组,arrays,shell,command-line-arguments,Arrays,Shell,Command Line Arguments,我正在尝试编写一个shell脚本,该脚本可以接受命令行上的多个元素作为单个数组处理。命令行参数格式为: exec trial.sh 1 2 {element1 element2} 4 我知道前两个参数是可以使用$1和$2访问的,但是如何访问由括号包围的数组,即由{}符号包围的参数 谢谢 此tcl脚本使用正则表达式解析来提取命令行的各个部分,将第三个参数转换为列表 拆分是在空格上完成的-这取决于您想在哪里使用,这可能是不够的 #!/usr/bin/env tclsh # # Sample ar

我正在尝试编写一个shell脚本,该脚本可以接受命令行上的多个元素作为单个数组处理。命令行参数格式为:

exec trial.sh 1 2 {element1 element2} 4 
我知道前两个参数是可以使用
$1
$2
访问的,但是如何访问由括号包围的数组,即由
{}
符号包围的参数


谢谢

此tcl脚本使用正则表达式解析来提取命令行的各个部分,将第三个参数转换为列表

拆分是在空格上完成的-这取决于您想在哪里使用,这可能是不够的

#!/usr/bin/env tclsh
#
# Sample arguments: 1 2 {element1 element2} 4

# Split the commandline arguments:
# - tcl will represent the curly brackets as \{ which makes the regex a bit ugly as we have to escape this
# - we use '->' to catch the full regex match as we are not interested in the value and it looks good
# - we are splitting on white spaces here
# - the content between the curly braces is extracted
regexp {(.*?)\s(.*?)\s\\\{(.*?)\\\}\s(.*?)$} $::argv -> first second third fourth

puts "Argument extraction:"
puts "argv: $::argv"
puts "arg1: $first"
puts "arg2: $second"
puts "arg3: $third"
puts "arg4: $fourth"

# Third argument is to be treated as an array, again split on white space
set theArguments [regexp -all -inline {\S+} $third]
puts "\nArguments for parameter 3"
foreach arg $theArguments {
    puts "arg: $arg"
}

您应该始终将可变长度参数放在末尾。但是如果你能保证你总是只提供最后一个论点,那么像这样的东西就足够了:

#!/bin/bash

arg1=$1 ; shift
arg2=$1 ; shift

# Get the array passed in.
arrArgs=()
while (( $# > 1 )) ; do
    arrArgs=( "${arrArgs[@]}" "$1" )
    shift
done

lastArg=$1 ; shift

您不需要使用
exec
来运行shell脚本。只需使用
sh
运行它。您好,很抱歉,我使用的是exec而不是sh,因为我后来重定向了标准输出,所以我想代码看起来更像。。。exec trial1.sh 1 2{element1 element2}4>$logfile即使使用
sh
运行输出,您仍然可以重定向输出,傻瓜。我是通过tcl运行shell脚本的,所以sh没有被识别为有效的Commandooh,我以为你是在shell中运行它的!哈哈,这就解释了为什么语法看起来如此不同寻常。我想你要找的可能是
lindex