2012-02-20 67 views
3

我想连接所有传递给我的bash脚本的参数,除了标志。在bash脚本中连接输入

因此,例如,如果脚本需要输入如下:

./myBashScript.sh -flag1 exampleString1 exampleString2 

我想要的结果是“exampleString1_exampleString2”

我能为输入的预定数量做到这一点(即2) ,但我怎么能做到这一点的任意数量的投入?

回答

2

这是一个丑陋的,但简单的解决方案:

echo $* | sed -e "s/ /_/g;s/[^_]*_//" 
+1

和错误。你有没有读过这个问题? – 2012-02-20 01:32:30

+0

@JoSo:是的,这属于它的(措辞不佳)规范。 – mvds 2012-02-20 01:35:07

+0

然而,你解释规范,你的解决方案是错误的。它甚至不删除任何参数。 – 2012-02-20 01:37:20

8
function concatenate_args 
{ 
    string="" 
    for a in "[email protected]" # Loop over arguments 
    do 
     if [[ "${a:0:1}" != "-" ]] # Ignore flags (first character is -) 
     then 
      if [[ "$string" != "" ]] 
      then 
       string+="_" # Delimeter 
      fi 
      string+="$a" 
     fi 
    done 
    echo "$string" 
} 

# Usage: 
args="$(concatenate_args "[email protected]")" 
+0

对不起,对于错误的外壳样式(非常冗长而且'[[...]]'不是便携式)是-1。使用'test'来替代我的解决方案来使用'$ {a:0:1}' – 2012-02-20 01:39:33

+0

@JoSo为什么'[[]]'不可移植? – Tyilo 2012-02-20 14:09:24

+0

这是bash,而不是POSIX sh。 (与'$ {a:0:1}'相同)。虽然有些人不关心,因为bash几乎安装在任何系统上,在这种情况下,它真的没有用(改用'test' alias'[']')。 – 2012-02-20 15:53:29

0
flag="$1" 
shift 
oldIFS="$IFS" 
IFS="_" 
the_rest="$*" 
IFS="$oldIFS" 

在此背景下,"$*"是你要找什么,它似乎。它很少是正确的选择,但是这是一个真正的选择。

或者,简单循环和连击:

flag="$1" 
shift 
the_rest="" 
pad="" 
for arg in "[email protected]" 
do 
    the_rest="${the_rest}${pad}${arg}" 
    pad="_" 
done 

$pad变量确保你不以$the_rest开始流浪下划线结束。

+0

O.P.如何在每个arg之间获得所需的'_'? – shellter 2012-02-20 01:31:55

+1

您可以设置IFS,使其第一个字符包含'_'来影响'$ *'连接的行为。 – 2012-02-20 01:33:53

2

这里有一段代码,实际上,我感到自豪的(这是很shell风格,我认为)

#!/bin/sh 

firsttime=yes 
for i in "[email protected]" 
do 
    test "$firsttime" && set -- && unset firsttime 
    test "${i%%-*}" && set -- "[email protected]" "$i" 
done 

IFS=_ ; echo "$*" 

我理解你的问题,以去除所有参数开头-

如果你只是想删除的论点- beginnnig开始序列:

#!/bin/sh 

while ! test "${1%%-*}" 
do 
    shift 
done 

IFS=_ ; echo "$*" 

如果你只是想删除的第一个参数:

#!/bin/sh 

shift 
IFS=_ ; printf %s\\n "$*" 
1

您还可以使用格式的字符串来连接ARGS。

# assuming flag is first arg and optional 
flag=$1 
[[ $1 = ${1#-} ]] && unset $flag || shift 

concat=$(printf '%s_' ${@}) 
echo ${concat%_} # to remove the trailing _ 

nJoy!