0

我正在尝试编写一个 shell 脚本,它可以在命令行上接受多个元素,将其视为单个数组。命令行参数格式为:

exec trial.sh 1 2 {element1 element2} 4 

我知道前两个参数可以使用$1and访问$2,但是如何访问括号包围的数组,即{}符号包围的参数?

谢谢!

4

2 回答 2

0

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

#!/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
于 2013-07-29T20:05:30.610 回答
0

此 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"
}
于 2013-07-29T19:59:26.320 回答