简体   繁体   中英

bash Syntax Madness - How to get third until last command line argument into an array

I have it working but cannot believe that the syntax should be that mad. All I want to do is to get the all arguments beginning with the third into an array.

Eg

script.sh foo bar value1 value2 value3

Should give me an array containing value1, value2, and value3. This array is the used to provide the parameters in a new function:

./runpy /dsnormalize.py "${values[@]}"

This works:

args=( "$@" )
length=$((${#args[@]}-2))
values=(${args[@]:$length:2})

Please tell me this is not the correct way. I usually ended up with a string containing all values.

How does bash handle strings and integers anyway? And is the difference between ${} and $()?

Thanks for your help, Karsten

The correct syntax is:

args_from_third=("{@:3}")

It's not necessary to insert the length, because the default is "the rest of the arguments".

It's certainly true that bash parentheses are complicated. The two I use here:

VARIABLE=(...)

This creates an array called VARIABLE , whose values are the whitespace delimited elements of the string ... .

"${@:start:length}"

This expands to length arguments starting at argument start ; if length is omitted, it uses all the rest of the arguments. The arguments are separated by space characters. Because the expression is quoted, each argument (but not the space delimiters) is treated as though it were quoted.

${...} covers a lot of possibilities, including substring, search-and-replace and case-changing. Look at the bash manual for details.

A much easier way to do this is by using shift to remove the fixed arguments.

first_arg=$1
second_arg=$2
shift 2
the_rest=("$@")

And:

How does bash handle strings and integers anyway? And is the difference between ${} and $() ?

${} is used to get a variable's value. The curly brackets are optional if you're just writing $foo , but they're required for anything more complicated, such as accessing elements of an array.

$() captures the output of a command, similar to backticks. This is different from $(( )) , which is what you're using.

$(( )) evaluates an arithmetic expression. It lets you do basic integer and boolean operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM