Skip to content
Advertisement

How to echo group of arguments passed to a script, instead of each individual argument

I have this very basic script:

#!/bin/bash
for x in "$@"; do
  echo $x
done

That when running it:

./script.sh qq ww ee rr tt yy uu ii oo pp

The output will be an echo of each argument like this:

qq
ww
ee
rr
tt
yy
uu
ii
oo
pp

How can I modify it to echo the arguments in a group of 4 or less (the last group), like this:

qq ww ee rr
tt yy uu ii
oo pp

Advertisement

Answer

You can use printf:

printf '%s %s %s %sn' "$@"
qq ww ee rr
tt yy uu ii
oo pp  

rematk: At the end of the last line you’ll get a space character for each missing element


Or use a bash substring expansion to get each array slice:

#!/bin/bash

n=4
for (( i = 1; i <= $#; i += n ))
do
    echo "${@:i:n}"
done
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement