I know that to loop through the alphabet, one can do
for c in {a..z}; do something; done
My question is, how can I loop through the first n
letters (e.g. to build a string) where n
is a variable/parameter given in the command line.
I searched SO, and only found answers doing this for numbers, e.g. using C-style for
loop or seq
(see e.g. How do I iterate over a range of numbers defined by variables in Bash?). And I don't have seq
in my environment.
Thanks.
The straightforward way is sticking them in an array and looping over that by index:
#!/bin/bash
chars=( {a..z} )
n=3
for ((i=0; i<n; i++))
do
echo "${chars[i]}"
done
Alternatively, if you just want them dash-separated:
printf "%s-" "${chars[@]:0:n}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With