命令行中的Shell脚本数组

时间:2013-07-29 18:35:58

标签: arrays shell command-line-arguments

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

exec trial.sh 1 2 {element1 element2} 4 

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

谢谢!

2 个答案:

答案 0 :(得分: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"
}

答案 1 :(得分: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
相关问题