Remove first element from $@ in bash

ArraysBash

Arrays Problem Overview


I'm writing a bash script that needs to loop over the arguments passed into the script. However, the first argument shouldn't be looped over, and instead needs to be checked before the loop.

If I didn't have to remove that first element I could just do:

for item in "$@" ; do
  #process item
done

I could modify the loop to check if it's in its first iteration and change the behavior, but that seems way too hackish. There's got to be a simple way to extract the first argument out and then loop over the rest, but I wasn't able to find it.

Arrays Solutions


Solution 1 - Arrays

Another variation uses array slicing:

for item in "${@:2}"
do
    process "$item"
done

This might be useful if, for some reason, you wanted to leave the arguments in place since shift is destructive.

Solution 2 - Arrays

Use shift.

Read $1 for the first argument before the loop (or $0 if what you're wanting to check is the script name), then use shift, then loop over the remaining $@.

Solution 3 - Arrays

firstitem=$1
shift;
for item in "$@" ; do
  #process item
done

Solution 4 - Arrays

q=${@:0:1};[ ${2} ] && set ${@:2} || set ""; echo $q

EDIT

> q=${@:1}
# gives the first element of the special parameter array ${@}; but ${@} is unusual in that it contains (? file name or something ) and you must use an offset of 1;

> [ ${2} ] 
# checks that ${2} exists ; again ${@} offset by 1
    > && 
    # are elements left in        ${@}
      > set ${@:2}
      # sets parameter value to   ${@} offset by 1
    > ||
    #or are not elements left in  ${@}
      > set ""; 
      # sets parameter value to nothing

> echo $q
# contains the popped element

An Example of pop with regular array

   LIST=( one two three )
    ELEMENT=( ${LIST[@]:0:1} );LIST=( "${LIST[@]:1}" ) 
    echo $ELEMENT

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHermsView Question on Stackoverflow
Solution 1 - ArraysDennis WilliamsonView Answer on Stackoverflow
Solution 2 - ArraysAmberView Answer on Stackoverflow
Solution 3 - ArraysnosView Answer on Stackoverflow
Solution 4 - ArraysJames AndinoView Answer on Stackoverflow