【问题标题】:Shell script array from command line来自命令行的 Shell 脚本数组
【发布时间】:2013-07-29 16:35:11
【问题描述】:

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

exec trial.sh 1 2 {element1 element2} 4 

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

谢谢!

【问题讨论】:

  • 您不需要使用exec 来运行shell 脚本。只需使用sh 运行它。
  • 嗨,对不起,我使用 exec 而不是 sh,因为我稍后会重定向标准输出,所以我想代码看起来更像... exec trial1.sh 1 2 {element1 element2} 4 >> $日志文件
  • 即使你使用sh 运行它,你仍然可以重定向输出,愚蠢的。 IO-redirection
  • 我正在通过 tcl 运行 shell 脚本,所以 sh 未被识别为有效命令
  • ,我以为你是在 shell 中运行它!大声笑,这就解释了为什么语法看起来如此不寻常。我认为lindex 可能是您正在寻找的。 lindex

标签: arrays shell command-line-arguments


【解决方案1】:

此 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"
}

【讨论】:

    【解决方案2】:

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

    #!/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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-08
      • 2013-03-03
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多