I have this very basic script:
JavaScript
x
#!/bin/bash
for x in "$@"; do
echo $x
done
That when running it:
JavaScript
./script.sh qq ww ee rr tt yy uu ii oo pp
The output will be an echo of each argument like this:
JavaScript
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:
JavaScript
qq ww ee rr
tt yy uu ii
oo pp
Advertisement
Answer
You can use printf
:
JavaScript
printf '%s %s %s %sn' "$@"
JavaScript
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:
JavaScript
#!/bin/bash
n=4
for (( i = 1; i <= $#; i += n ))
do
echo "${@:i:n}"
done