12

I have a quick question. I just wanted to know if it was valid format (using bash shell scripting) to have a counter for a loop in a file name. I am thinking something along the lines of:

for((i=1; i <=12; i++))
do
  STUFF
  make a file(i).txt
1
  • Look at this Commented Jun 22, 2012 at 18:34

2 Answers 2

11

Here's a quick demonstration. The touch command updates the last-modified time on the file, or creates it if it doesn't exist.

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

You may want to add leading zeroes to the cases where $i is only 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, and so on, instead of file1.txt, file2.txt.

Sign up to request clarification or add additional context in comments.

1 Comment

Good explanation. I would also add how ">" can be used to create files and truncate them if they already exist.
8

If you only want to make a bunch of files and don't need the loop for anything else, you can skip the loop altogether:

touch file{1..12}.txt

will make them all in one command.

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

touch file{01..12}.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.