Linux – bash command-line arguments are placed in an array and the array is subset, based on the parameter values

bash command-line arguments are placed in an array and the array is subset, based on the parameter values… here is a solution to the problem.

bash command-line arguments are placed in an array and the array is subset, based on the parameter values

I’m trying to get input parameters for my bash script.
testbash.sh 4 1 2 4 5 Science p *
I want to get these parameters as an array, and I use $@ to get them all into one array. Now based on the first parameter, I need to subset the rest. Here the first number is 4, so from the second argument to the fifth argument should be saved as one array, such as [1 2 4 5], and the rest of the arguments should be saved in another array.

I tried

Array=( $@ )
len=${#array[@]}
args=${array[@]:0:$len-${array[1]}}
Echo $args

I

tried this to get the first part, but when I run this “testbash.sh 4 1 2 4 5 Science a p*”, I get an error syntax error in the expression (the error flag is “:-4”

).

Solution

Here’s one way:

FIRST_SET=("${@:2:$1}")
REST=("${@:$(($1+2))}")

This works directly from the parameters instead of using an intermediate array. It would be easy to use intermediate arrays in much the same way, but remember that array indexes start at 0, while parameter indexes effectively start at 1 (since parameter 0 is the command name).

Note that quotes are important: without them, command-line arguments will pass extra time through glob expansion and word segmentation; In effect, you lose the ability to reference command-line arguments.

Related Problems and Solutions