docs
  • Overview
  • 🐍 PYTHON
    • Type Hints
    • PEP8 Style Guide for Python Code
    • 🏡Pipenv
    • Pathlib
  • 🕸Django
    • 🗄models
      • 🎯Best Practices
      • 🚦Django Signals
    • ⚙️ settings
    • DRF
      • Serializer
      • Authentication
      • Permissions
      • Viewsets
    • Testing
      • Faker and Factory Boy
    • 🧪Test Coverage
    • 💦Python-Decouple
    • Django Tips:
    • 💾Django ORM Queryset
    • Custom Exceptions
    • Celery
    • Resources
  • Deploy
    • 🚀Django Deployment
    • 🔒Setup SSL Certificate
  • 💾Database
    • MongoDB
  • 🛠️DevOps
    • 🖥Scripting
      • A First Script
      • Loops
      • Test
      • Variables
      • External programs
      • Functions
    • Command Line Shortcuts
    • Basic Linux Commands
    • 🎛Microservices
    • 🐳Docker
      • Docker Commands
      • Docker Compose
      • Django project
    • Kubernates
  • 📝Software IDE
    • EditorConfig
    • Linters
    • VsCode
Powered by GitBook
On this page
  • For Loops:
  • While Loops:

Was this helpful?

  1. DevOps
  2. 🖥Scripting

Loops

for loops and while loop in shell scripting

Most languages have the concept of loops: If we want to repeat a task twenty times, we don't want to have to type in the code twenty times. we have for and while loops in the shell.

For Loops:

for loops iterate through a set of values until the list is exhausted:

#!/bin/sh
for i in 1 2 3 4 5
do
  echo "Looping ... number $i"
done
#!/bin/sh
for i in hello 1 * 2 goodbye 
do
  echo "Looping ... i is set to $i"
done

Try it without the * and grasp the idea.

While Loops:

#!/bin/sh
INPUT=hello
while [ "$INPUT" != "bye" ]
do
  echo "Please type something in (bye to quit)"
  read INPUT
  echo "You typed: $INPUT"
done

The colon (:) always evaluates to true

#!/bin/sh
while :
do
  echo "Please type something in (^C to quit)"
  read INPUT_STRING
  echo "You typed: $INPUT_STRING"
done

While with case

#!/bin/sh
while read f
do
  case $f in
	hello)		      echo English	;;
	howdy)		      echo American	;;
	gday)		        echo Australian	;;
	bonjour)	      echo French	;;
	"guten tag")	  echo German	;;
	*)		         echo Unknown Language: $f ;;
  esac
done < some_file

Tips: To create multiple file at once

mkdir file_name{1,2,3,new,old}.py

And this can be done recursively, too:

$ cd /
$ ls -ld {,usr,usr/local}/{bin,sbin,lib}
PreviousA First ScriptNextTest

Last updated 5 years ago

Was this helpful?

🛠️