Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I am able to do this,

array=(2 46 7 4 2 1 1 1 23 4 5)
store=(${array[*]:5:5})
echo ${store[@]}  # print 1 1 1 23 4 5

Now instead of extracting the 5 elements from position 5 from a user array, I need to extract command-line args from 5 and onward. I tried similar way but I am getting empty output

store=(${$[*]:5:5})  # <----------------- Something to be changed here?
echo ${store[@]}  # EMPTY OUTPUT

Any help, how to store n args from position mth onward in a array?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

In bash (and also zsh and ksh93, the general form of parameter expansion or Substring Expansion is:

${parameter:offset:length}

If the length is omitted, you will get from offset to the end of parameter.

In your case:

array=(2 46 7 4 2 1 1 1 23 4 5)
store=( "${array[@]:5}" )
printf '%s\n' "${store[@]}"

will generate from 6th element to the last element.

With $@:

printf '%s\n' "${@:5}"

will generate from $5 to the end of positional arguments.

Also note that you need to quote the array variable to prevent split+glob operator on its elements.


With zsh, you can use another syntax:

print -rl -- $argv[5,-1]
share|improve this answer
    
Ok, I understand that, I am able to do it for user defined array, but my question is how do I extract from commandline args i.e $5 to end. –  mtk yesterday
    
@mtk: Just using it as-is. Added more details to the answer. –  cuonglm yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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