Using the count variable in a file name

I have a quick question. I just wanted to know if it was a valid format (using bash shell scripting) in order to have a counter for the loop in the file name. I think something like:

for((i=1; i <=12; i++)) do STUFF make a file(i).txt 
+8
variables bash loops
source share
2 answers

If you only want to create a bunch of files and don’t need a loop for anything else, you can skip the loop completely:

 touch file{1..12}.txt 

will do everything in one team.

If you have Bash 4, you can get leading zeros:

 touch file{01..12}.txt 
+3
source share

Here is a quick demo. The touch command updates the time the file was last modified or creates it if it does not exist.

 for ((i=1; i<=12; i++)); do filename="file$i.txt" touch "$filename" done 

You can add leading zeros in cases where $i is just one digit:

 for ((i=1; i<=12; i++)); do filename="$(printf "file%02d.txt" "$i")" touch "$filename" done 

This will result in file01.txt , file02.txt , etc. instead of file1.txt , file2.txt .

+8
source share

All Articles