tags:

views:

1391

answers:

1

(edited to fit the answer)

Looking the "Array" section in the bash(1) man page, I didn't find a way to slice a bash array.

So I came up with this overly complicated function:

#!/bin/bash

# @brief: slice a bash array
# @arg1:  output-name
# @arg2:  input-name
# @args:  seq args
# ----------------------------------------------
function slice() {
   local output=$1
   local input=$2
   shift 2
   local indexes=$(seq $*)

   local -i i
   local tmp=$(for i in $indexes 
                 do echo "$(eval echo \"\${$input[$i]}\")" 
               done)

   local IFS=$'\n'
   eval $output="( \$tmp )"
}

Used like this:

$ A=( foo bar "a  b c" 42 )
$ slice B A 1 2
$ echo "${B[0]}"  # bar
$ echo "${B[1]}"  # a  b c

Is there a better way to do that?

+7  A: 

See the Parameter Expansion section in the Bash man page.

A=( foo bar "a  b c" 42 )
B=("${A[@]:1:2}")
echo "${B[@]}"    # bar a  b c
echo "${B[1]}"    # a  b c
Dennis Williamson
Cool. I looked in the Array section, and did not see it there.
Chen Levy