WanttoBeScripter147
WanttoBeScripter147

Reputation: 65

Trying to create a bash script loop over some numbers using a counter

I am very new to Bash Scripting, and have just started very recently. I have set myself a goal of trying to make a working loop with a counter. What I want to do is make the script loop over 4 numbers (e.g. 1 3 2 0 in that order). In the loop, I want to create the file i.txt in my current directory, and I would like i to be the counter value.

My problem is that I am not too sure on how to make a working counter in a text file, and after doing some research, I have ended up quite stumped. I would really appreciate any help you can give me so I can learn and get better. I'm sorry for not having some sort of base code that I can show you as, at the moment I am just trying to figure out how I would make everything work. Thanks!

Upvotes: 0

Views: 1089

Answers (2)

QQVEI
QQVEI

Reputation: 49

Alternative format:

BEGIN=1
END=5

for i in $(seq $BEGIN $END);
do
    echo $i
done

Upvotes: -1

John Kugelman
John Kugelman

Reputation: 361565

Since you want to iterate over the numbers in a particular non-sequential order, the simplest way is to use a for loop that lists each of the numbers explicitly. Then you can use touch inside the loop to create each of the files.

for i in 1 3 2 0; do
    touch "$i".txt
done

For what it's worth, if you were iterating over the numbers in sequential order you could write the loop one of these ways instead:

for ((i = 0; i < 4; i++)); do
    ...
done

or

for i in {0..3}; do
    ...
done

You could even condense it to a single touch command if that's all you were doing in the loop.

touch {0..3}.txt

Upvotes: 6

Related Questions