User Tools

Site Tools


linux:basic-bash-logic

Bash logic

Date: Mon Sep 24 11:03:02 EDT 2018

Basic Bash scripting and logic examples

Use the help command to get help:

$ help [[
$ help [
$ help test

Testing

Test true if file exists:

#!/bin/bash
if [[ -a "example.txt" ]] ; then
    echo "it exists"
else
  echo "it doesn't exist"
fi

Test true if string 'b' sorts after string 'a':

#!/bin/bash
if [[ b > a ]] ; then
  echo "True"
else
  echo "False"
fi

Test true if integer 4 is greater than 5.

#!/bin/bash
if [[ 4 -gt 5 ]] ; then
  echo "four is greater than five"
  echo "Creating file four.txt"
  touch four.txt
  sleep 1
  echo "..."
  sleep 1
  echo "..."
  sleep 1
  echo "file four.txt was created"
else
  echo "four is less than five"
  echo "Creating file five.txt"
  touch five.txt
  sleep 1
  echo "..."
  sleep 1
  echo "..."
  sleep 1
  echo "file five.txt was created"
fi

For Loops

Simple loop from 1 to 10:

#!/bin/bash
for i in $(seq 1 10) ; do
    echo "$i"
done

While Loops

Print loop until less than 10:

#!/bin/bash
i=0
while [[ "$i" -lt 10 ]]
do
    echo "$i"
    ((i++))
done

Note that, if done on the command line and not from a script file, "$i" is now equal to 10. Otherwise, you will have to reinitialize it.

Print loop until greater than 0:

#!/bin/bash
i=10
while [[ "$i" -gt 0 ]]
do
    echo "$i"
    ((i--))
done

Until Loops

Print loop until i = 10:

#!/bin/bash
i=0
until [[ "$i" -eq 10 ]]
do
    echo "$i"
    ((i++))
done

Nesting

List only directories in current directory:

#!/bin/bash
for i in * ; do
  if [[ -d "$i" ]] ; then
        echo "$i"
    fi
done

List only files in current directory:

#!/bin/bash
for i in * ; do
  if [[ -f "$i" ]] ; then
        echo "$i"
    fi
done

Case statements

#!/bin/bash

printf "\nPick a number 1-4: \n"

read ANSWER

case $ANSWER in
  1)
    printf "\nPrinting first option.\n\n"
    ;;
  2)
    printf "\nPrinting second option.\n\n"
    ;;
  3)
    printf "\nPrinting third option.\n\n"
    ;;
  4)
    printf "\nPrinting fourth option.\n\n"
    ;;
  *)
    printf "\nNot an option.\n\n"
    exit
    ;;
esac

Select statements

#!/bin/bash

options="Hello Goodbye"

select i in $options ; do
  if [[ "$i" = "Hello" ]] ; then
    echo "Hi Back!"
  elif [[ "$i" = "Goodbye" ]] ; then
    echo "Goodbye!"
    exit
  else
    echo "It's like goodbye -- you still exit."
    exit
  fi
done
linux/basic-bash-logic.txt · Last modified: 2019/01/21 11:12 by seanburns