Monday, 11 February 2019

Bash - Conditions and loops

Again, an aide memoire

A Bash script that tests for a single input, and moans if none are found: -

cat plob.sh 

#!/bin/bash

if [ -z "$1" ]
  then
    echo "For what product are you creating this ?"
    exit 1
  else
    echo $1

fi

With no argument ....

./plob.sh 

For what product are you creating this ?

With one argument ...

./plob.sh BPM

BPM

With multiple arguments ....

./plob.sh BPM ODM

BPM

In other words, only the first argument is used ...

A Bash script that tests for TWO arguments: -

cat plab.sh 

#!/bin/bash
if [ $# = 2 ]
then
echo "Nice arguments"
else
echo "More arguments, please"
exit 1
fi

With no argument ...

./plab.sh 

More arguments, please

With one argument ...

./plab.sh BPM

More arguments, please

With two arguments ...

./plab.sh BPM ODM

Nice arguments

A Bash script that tests for TWO arguments: -

cat plib.sh 

#!/bin/bash
echo $#
if [ -z "$1"  ] & [ -z "$2" ]
then
        echo "Usage: Two arguments please"
        exit 1
else
echo $1 $2
fi

With no argument ...

./plib.sh 

0
Usage: Two arguments please

./plib.sh BPM

1
Usage: Two arguments please

./plib.sh BPM ODM

2
BPM ODM

So, for reference, we're using the following: -

$# - Counts the arguments
#1 - Argument 1
#2 - Argument 2
-z - Checks whether the arguments are empty 

From a looping perspective, I've used this one many times before ....

A Bash script that unpacks some TAR files: -

for i in /tmp/*.tar.gz; do tar xvzf $i -C /tmp/snafu; done

This is with what we started: -

ls -al *.tar.gz

-rw-r--r--  1 hayd  wheel  135 11 Feb 16:22 billing.tar.gz
-rw-r--r--  1 hayd  wheel  154 11 Feb 16:22 docs.tar.gz
-rw-r--r--  1 hayd  wheel  138 11 Feb 16:22 preso.tar.gz

and this is what we ended: -

ls -al /tmp/snafu/

total 0
drwxr-xr-x   6 hayd  wheel  192 11 Feb 16:23 .
drwxrwxrwt  21 root  wheel  672 11 Feb 16:22 ..
-rw-r--r--   1 hayd  wheel    0 11 Feb 16:22 Expenses.xls
-rw-r--r--   1 hayd  wheel    0 11 Feb 16:21 Journal.doc
-rw-r--r--   1 hayd  wheel    0 11 Feb 16:22 Presentation.ppt
-rw-r--r--   1 hayd  wheel    0 11 Feb 16:21 Readme.doc

Final thing, with tar, we use -C to specify the target directory and for unzip, we use -d to specify the target directory.

No comments:

Following up ... defining K8S Services using YAML

As a fup to this: - Playing with Kubernetes deployments and NodePort services life is SO much easier if I choose to define the service...