Shell Scripting Knowledge Base
for loop
Example(s)
Create multiple files based on a template and make substitutions to those files.
for i in {32..43}
do
cp -v 31.php $i.php
sed -i "s/pageID = .*;/pageID = $i;/" $i.php
done
Make copies of existing files and edit the copies.
for i in {106..128}; do cp -v "$i".php "$i"__mine.php; done
for i in {106..128}; do sed -i 's/".php";/"__mine.php";/' "$i"__mine.php; done
Create sequentially numbered folders, method 1/3.1
for i in {1..9}; do
mkdir -v step0"$i"
done
Create sequentially numbered folders, method 2/3.1
for i in {1..9}; do mkdir -v step0"$i" ; done
for i in {2..12}; do curl -O https://www.aa.org/assets/en_US/en_tradition"$i".pdf ; done
for i in {10..12}; do mkdir -v "$i" && cd "$i" && touch index.php && cd ../; done
Create sequentially numbered folders, method 3/3 (brace expansion).1
mkdir -v step0{1..9}
Execute a command on all files in present working directory.2
for i in *; do convert $i -resize 600 $i; done for i in *; do sed 3i"PLACEHOLDER" $i; done
Iterate over a range using variables.
#!/bin/bash
FIRST=21
LAST=24
FILE="single_page__mine.html"
for i in $(seq $FIRST $LAST)
do
sed -n '/<!-- CONTENT GOES HERE: -->/,/<!-- END CONTENT -->/p' $i.php >> $FILE;
cat >> $FILE << CODE
<div class="page_nav">
<span class="box__pageID">$i/$LAST</span>
</div>
CODE
done
Only loop through folders (simple).3
for d in */ ; do cp -v 00__template.php $d/index.php; done
Only loop through folders (a little more complex).3
for f in *; do if [ -d "$f" ]; then # $f is a directory fi done
Compress a bunch of folders
Folders/files to be compressed.
for i in {1..9} ; do tar -czvf /destination/folder/path/and/filename/0"$i"/0"$i".tar.gz 0"$i"/ ; done
for i in {1..9} ; do tar -czvf ~/01__archive/recovery/daily_readings/daily_reflections/0"$i"/0"$i".tar.gz 0"$i"/ ; done