3

Trying to slice array while taking args from command prompt as the array items. The problem is that the positional parameters for slicing do not work as I expect. How do I slice array taking params from prompt?

./arrays.bash awesome cool strong cute awesome

I want

  arr=$@ 
  echo ${arr[*]:0:2} #awesome cool

I get

  arr=$@ 
  echo ${arr[*]:0:2} # aw

I read the post: How to slice an array in bash but I believe my question is different. Seems to be that the difficulty here is that because I am getting my array values from the command prompt, or not, idk. It does behave as expected when array is included in the script as a variable. This is from learnyoubash so just adjusting the indexes to cut out characters instead of entire values, which does return the correct answer, is not a valid solution to the problem. My solution incorrect but working solution https://github.com/nodeschool/discussions/issues/2241

Mote Zart
  • 636
  • 1
  • 9
  • 27

1 Answers1

5

To store $@ in an array you must write:

arr=("$@")

Without the parentheses $arr is just a single string.

John Kugelman
  • 307,513
  • 65
  • 473
  • 519
  • Also, you should almost always use `[@]` with arrays, and double-quote it (e.g. `"${arr[@]:0:2}"`) to avoid trouble with funny characters in the array elements. – Gordon Davisson Jan 14 '18 at 05:33