BASH: Some of My Looping Command Collections

Here are several of my BASH commands collection related to looping which I frequently used. This list will be always updated for reference and knowledge base.

1. Copy .htaccess file under /home/website1/public_html to all directories and sub-directories under /home/website2/public_html excluding .svn directories:

cd /home/website2/public_html
for i in $(find -type d | egrep -v .svn); do cp /home/website1/.htaccess $i; done

2. Rename all files and directories in current path to .bak:

for i in *; do mv $i $i.bak; done

3. Remove .bak extension in all files and directories in current path (undo for command #2):

for i in *; do mv $i $(basename $i .bak); done

4. Return number of files in each directory and sub-directory:

find -type f -execdir pwd \; | sort | uniq -c

5. Generate 24 files with 10 MB in size under current directory:

for i in $(seq 1 1 24); do dd bs=1024 count=10000 if=/dev/zero of=file.$i; done

6. Generate some random data for database foo and table bar in 3 fields (val1,val2,val3):

mysql -e "INSERT INTO foo.bar (val1, val2, val3) VALUES ((SELECT floor(rand() * 10) as randNum), (SELECT floor(rand() * 10) as randNum),(SELECT floor(rand() * 10) as randNum));"

 

Your share and opinion is welcome!