Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first element from $@ in bash [duplicate]

Tags:

arrays

bash

People also ask

How do I remove the first part of a string in bash?

Using the parameter expansion syntax To remove the first and last character of a string, we can use the parameter expansion syntax ${str:1:-1} in the bash shell. 1 represents the second character index (included). -1 represents the last character index (excluded).

What does $@ do in bash script?

Meaning. In brief, $@ expands to the arguments passed from the caller to a function or a script. Its meaning is context-dependent: Inside a function, it expands to the arguments passed to such function. If used in a script (outside a function), it expands to the arguments passed to such script.

What is the difference between $@ and $* in bash?

There is no difference if you do not put $* or $@ in quotes. But if you put them inside quotes (which you should, as a general good practice), then $@ will pass your parameters as separate parameters, whereas $* will just pass all params as a single parameter.

Does $@ include $0?

Difference between “$0” and “$@” in Unix shell scripts.. They are entirely different. $0 is the name of the script; "$@" expands to the command-line arguments.


Use shift?

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html

Basically, 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 $@.


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.


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

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