Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through the first n letters of the alphabet in bash

Tags:

bash

loops

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.

like image 549
thor Avatar asked Dec 12 '22 00:12

thor


1 Answers

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}"
like image 124
that other guy Avatar answered May 07 '23 23:05

that other guy