Saturday, November 30, 2019

[Unix / Linux Shell Tutorial - Lession8] Loops

  1. #!/bin/bash
  2. # Basic while loop
  3. counter=1
  4. while [ $counter -le 10 ]
  5. do
  6. echo $counter
  7. ((counter++))
  8. done
  9. echo All done



  1. #!/bin/bash
  2. # Basic until loop
  3. counter=1
  4. until [ $counter -gt 10 ]
  5. do
  6. echo $counter
  7. ((counter++))
  8. done
  9. echo All done



  1. #!/bin/bash
  2. # Basic for loop
  3. names='Stan Kyle Cartman'
  4. for name in $names
  5. do
  6. echo $name
  7. done
  8. echo All done



  1. #!/bin/bash
  2. # Basic range in for loop
  3. for value in {1..5}
  4. do
  5. echo $value
  6. done
  7. echo All done



  1. #!/bin/bash
  2. # Basic range with steps for loop
  3. for value in {10..0..2}
  4. do
  5. echo $value
  6. done
  7. echo All done


  1. #!/bin/bash
  2. # Make a php copy of any html files
  3. for value in $1/*.html
  4. do
  5. cp $value $1/$( basename -s .html $value ).php
  6. done


  1. #!/bin/bash
  2. # Make a backup set of files
  3. for value in $1/*
  4. do
  5. used=$( df $1 | tail -1 | awk '{ print $5 }' | sed 's/%//' )
  6. if [ $used -gt 90 ]
  7. then
  8. echo Low disk space 1>&2
  9. break
  10. fi
  11. cp $value $1/backup/
  12. done


  1. #!/bin/bash
  2. # Make a backup set of files
  3. for value in $1/*
  4. do
  5. if [ ! -r $value ]
  6. then
  7. echo $value not readable 1>&2
  8. continue
  9. fi
  10. cp $value $1/backup/
  11. done



  1. #!/bin/bash
  2. # A simple menu system
  3. names='Kyle Cartman Stan Quit'
  4. PS3='Select character: '
  5. select name in $names
  6. do
  7. if [ $name == 'Quit' ]
  8. then
  9. break
  10. fi
  11. echo Hello $name
  12. done
  13. echo Bye




No comments:

Post a Comment

Back to Top