Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Advanced Bash :: Array slicing and compaction in bash
# Advanced Bash :: Array slicing and compaction in bash
# TL;DR
X=(something 'whatever' "i have more S P A C E S than i can give away. arent you jealous?")
# ${X[@]} the usual whole array
# ${X[@]:index:length} slice from index to index+length-1 inclusive
# ${X[@]::length} slice from 0 to length-1 inclusive
# ${X[@]:index} slice from index to end of array inclusive
# X=( "${X[@]}" ) compact X
# X=( "${X[@]::$INDEX}" "${X[@]:$((INDEX+1))}" ) remove element at INDEX and compact array
# Examples:
Y=( 000 111 222 333 )
echo "${Y[@]:2}"
# 222 333
echo "${Y[@]:1:3}"
# 111 222 333
echo "${Y[@]::1}"
# 000
INDEX=2
# this wont work in some situations
unset Y[$INDEX]
echo "${Y[@]}"
# 000 111 333
echo "${#Y[@]}"
# 3 # looks correct, but it's not
echo "${Y[3]}"
# 333 # you might be thinking: '???'
# this is because bash arrays are sparse, like a NoSQL
echo "${#Y[@]}"
# 3
Y[9999]=9999
echo "${#Y[@]}"
# 4
# see?
# when dealing with arrays that are compact (no unset elements) AT LEAST UNTIL INDEX+1,
# this will remove the element at INDEX
Y=( "${Y[@]::$INDEX}" "${Y[@]:$((INDEX+1))}" )
echo "${Y[@]}"
# 000 111 333 9999
echo "${Y[3]}"
# 9999
# so you just want a sparse array to be compact right now?
Y=( 000 111 222 333 )
Y[9999]=9999
echo "${Y[@]}"
# 000 111 222 333 9999
echo "${Y[9999]}"
# 9999
Y=( "${Y[@]}" ) # compact
echo "${Y[@]}"
# 000 111 222 333 9999
echo "${Y[4]}"
# 9999
# fin.
@mauroretch

This comment has been minimized.

Copy link

mauroretch commented Sep 1, 2017

Thank you very much. It help me to understand slice from index to end of array inclusive.

@felipeamarante

This comment has been minimized.

Copy link

felipeamarante commented Jul 24, 2018

thanks! great cheat sheet 👍

@mrsalem13

This comment has been minimized.

Copy link

mrsalem13 commented Apr 23, 2019

what do you mean about compact X ?

@mrgh

This comment has been minimized.

Copy link

mrgh commented Apr 29, 2019

@mrsalem13
have a look at line 54

@passionfruit18

This comment has been minimized.

Copy link

passionfruit18 commented Jun 12, 2019

Line 62. Three types of brackets, plus quotes. Bash~ Just trying to pack as much good stuff in there as possible...

@solodino

This comment has been minimized.

Copy link

solodino commented Dec 17, 2019

Thanks! Exactly the information I was looking for to solve a "puzzling" issue in my script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.