Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit for bash loop

Tags:

linux

bash

loops

I have problem with mass creation dummy files and directories. I want to create something like this:

dummy_directory_1/dummy_file_1
dummy_directory_2/dummy_file_2
dummy_directory_3/dummy_file_3

using loop:

for(( i=1; $i <=1000; i++ )); do 
   mkdir $(date --date="$i day ago" +%Y%m%d%H%M%S); 
   touch $(date --date="$i day ago" +%Y%m%d%H%M%S)/$(date --date="$i day ago" +%Y%m%d%H%M%S)_file; 
done

Not all file are being created because I get following errors:

touch: cannot touch `20140211230556/20140211230556_file': No such file or directory
touch: cannot touch `20131105230559/20131105230559_file': No such file or directory
touch: cannot touch `20130529000604/20130529000604_file': No such file or directory

Do you know if bash/linux has some limits for file creation? I had similar problem when I made script for searching many files using grep. If i change loop $i<=10 it works. Please help.

like image 502
user3461823 Avatar asked Mar 25 '14 22:03

user3461823


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

Does bash have infinite loops?

An infinite loop in Bash or any other programming language refers to a loop that is continuous i.e., its terminating condition is never met or its executing condition forever stays true. Such loops in any programming language are very simple to write.

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.


1 Answers

Your code only works if the two date calls generating the name of the directory are executed within the same second, if that happens to change inbetween you end up with two different values for the direcory name.

Try to store the value in a variable first:

for(( i=1; i <= 1000; i++ )); do
    name=$(date --date="$i day ago" +%Y%m%d%H%M%S)
    mkdir -p "$name" &&
    touch "$name/${name}_file" ||
    break
done
like image 190
mata Avatar answered Sep 20 '22 23:09

mata