the for loop

when the user wants a command to be run exactly x times

# one-liner for-loop
for i in $(seq 1 5); do echo $i; done;

# multi-liner for-loop
for ((n=1; n<=17; n++))
do
    printf "do this and that\n";
done
# for example generate a file with 1 million lines
# and messure the time it takes for the computer to generate those lines
time for i in $(seq 1 1000000); do echo "generating line number $i"; echo "$i another line to test if the editor can handle it" >> temp.txt; done

took lenovo t440 laptop with i5 and ssd:

generating line number 999996
generating line number 999997
generating line number 999998
generating line number 999999
generating line number 1000000

real	0m27.398s
user	0m19.728s
sys	0m7.492s

half a minute to generate this file

then for some reason it generates 1 million and 1 line

wc -l temp.txt; # count line numbers in file
1000001 temp.txt

du -hs temp.txt; # file syze
54M	temp.txt; # 54MBytes

not exactly 1 million

while loop

if user wants a “infinity” “endless” loop

for example this elaborate “one liner”

will give the user constant updates on changes to dmesg (the last 20 lines)

while also giving the user update on what is going on with the harddisks

while true; do echo '===========' date '+DATE: %Y-%m-%d TIME: %H:%M:%S'; dmesg|tail -n20; lsblk -o "NAME,MAJ:MIN,RM,SIZE,RO,FSTYPE,MOUNTPOINT,UUID"; sleep 1; clear; done

conditional while loop example:

#!/bin/sh
a=0
while [ $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

iterate over files

# find all files of type m4a in the current dir and all subdirs
# and pass the found files to another scripts
find . -type f -iname "*.m4a" -exec /scripts/convert.sh {} \;

# find all picture.jpg files larger than 45k
# in the current dir and all subdirs
# and copy them to dir /path/to/recovery
find . -type f -size +45k -iname "*.jpg" -exec cp -rv {} /path/to/recovery \;

liked this article?

  • only together we can create a truly free world
  • plz support dwaves to keep it up & running!
  • (yes the info on the internet is (mostly) free but beer is still not free (still have to work on that))
  • really really hate advertisement
  • contribute: whenever a solution was found, blog about it for others to find!
  • talk about, recommend & link to this blog and articles
  • thanks to all who contribute!
admin