Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active March 7, 2022 05:27
Show Gist options
  • Save Integralist/eb7bf0d8f3b7d9958f13 to your computer and use it in GitHub Desktop.
Save Integralist/eb7bf0d8f3b7d9958f13 to your computer and use it in GitHub Desktop.
Zsh and Bash Array Shift (remove first item from the Array)
array=(foo, bar, baz)
echo ${array[@]} # => foo, bar, baz
array=("${array[@]:1}")
echo ${array[@]} # => bar, baz
array=("${array[@]:1}")
echo ${array[@]} # => baz
array=(foo, bar, baz)
echo $array # => foo, bar, baz
array=("${(@)array:1}")
echo $array # => bar, baz
array=("${(@)array:1}")
echo $array # => baz
# UPDATE: this works as well and is less confusing syntax
array=(${array:1})
@Integralist
Copy link
Author

Be aware that you'll get the trailing , when extracting an item from the Array.

To work around that, you need to first get the index of the , and then substring it out...

PIPELINE="foo, bar, baz"
ARRAY=($PIPELINE)                # Converting the build parameter into an Array
PROJECT=${ARRAY[0]}              # Extract first element
INDEX=$(expr index "$PROJECT" ,) # Get index of the , character
PROJECT=${PROJECT:0:index-1}     # Reassign PROJECT variable without , character

You can also avoid ALL of this if you don't make it a comma separated list

@olejorgenb
Copy link

olejorgenb commented Jun 24, 2016

For zsh (might work in bash too) (might require some options)

array=($array[2,-1])

or destructively

shift array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment