Capturing all arguments after the nth argument and concatenating them together in bash

So I have a bash script that should take an arbitrary number of command line arguments and put them on one line

User input example:

give <environment> <email> <any number of integers separated by spaces>
give testing stuff@things.com 1 2 3 4 5

I want to get all arguments from $ 3 to $ # and combine them into a string.

My (possibly awful) solution now

if [ $# -gt 3 ]
then
    env="env="$1
    email="email="$2
    entList=""

    for i in {3..$#}
    do
        if [ $i -eq 3 ]
            then
                    entList=$3
                    shift
            fi;
            if [ $i -gt 3 ]
            then
                    entList=$entList","$3
                   shift
            fi;
     done
fi;

I handle the case of having only three arguments a little differently and this one works fine.

The final value $entListgiven in the example give testing stuff@things.com 1 2 3 4 5should be:1,2,3,4,5

Right now, when I run this, I get the following errors:

/usr/local/bin/ngive.sh: line 29: [: {3..5}: integer expression expected
/usr/local/bin/ngive.sh: line 34: [: {3..5}: integer expression expected

Lines 29 and 34:

line 29: if [ $i -eq 3 ]
line 34: if [ $i -gt 3 ]

Any help would be appreciated.

+5
source share
3 answers

You are on the right track. Here is my suggestion:

if [ $# -ge 3 ]; then

  env="$1"
  email="$2"
  entlist="$3"

  while shift && [ -n "$3" ]; do
    entlist="${entlist},$3"
  done

  echo "entlist=$entlist"

else

  echo "Arguments: $*"

fi

, . , env=env=$1, , , , , , , .

+6

:

all=( ${@} )
IFS=','
threeplus="${all[*]:3}"
+4

, , :

for i in {3..$#}

, if :

if [ {3..$#} -eq 3 ]

.

for, C:

for ((i = 3; i <= $#; i++))

:

if (( $# > 3 ))

if (( i == 3 ))

if (( i > 3 ))

:

env="env=$1"
email="email=$2"

entList="$entList,$3"

although quotation marks are not needed because word separation is not performed on the right side of the job, and you do not assign special characters such as spaces, semicolons, channels, etc.

+1
source

All Articles