5

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

1 Answer 1

7

To store $@ in an array you must write:

arr=("$@")

Without the parentheses $arr is just a single string.

1
  • 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. Jan 14, 2018 at 5:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.