Bash basics

Shebang

Bash script shebang:

#!<path to bash binary>

For example:

#!/bin/bash

In order to get the path to bash binary:

which bash

Outputs:
/bin/bash

Execute a script

Make ‘testScript’ file executable

In order to execute a file by a user, that user has to have ‘execute’ permissions for the file. Give ‘execute’ permissions to all users:

chmod +x testScript

Execute ‘testScript’ file from the directory where it is located

./testScript

The testScript is executed using the binary defined in the $SHELL environment variable.

Execute ‘testScript’ file using the bash binary

bash -c "./testScript"

This way of executing files may be useful while working with Docker containers. For example, in order to execute ‘testScript’ file in a container:

docker exec <containerName> bash -c ". <somePath>/testScript"

Get a substring from a string

Get a substring from a string using Bash substring expansion

${parameter:offset}
${parameter:offset:length}

The first element index is 0. As an example let’s take all characters from the 4th till the last one:

s=200730
echo ${s:4}
Output: 30

In another example we will take two characters starting from the 2nd one:

s=200730
echo ${s:2:2}
Output: 07

Get a substring from a string using cut command

echo ${s} | cut -c<start>-<end>

The first element index is 1. In the example below, we take characters from the 3rd till the 4th, included:

s=200730
echo ${s} | cut -c3-4
Output: 07

Loop through a range of values

Bash offers us multiple possibilities to loop through a range of values. The range borders can be defined statically or dynamically.

Example 1. Looping through a range from 5 to 10 using for loop:

r="5 6 7 8 9 10"
for i in ${r}; do echo ${i}; done
Output:
5
6
7
8
9
10

Example 2. Looping through a dynamically defined range from 5 to 10 using for loop:

s=5
e=10
for i in $( seq ${s} ${e} ); do echo ${i}; done
Output:
5
6
7
8
9
10

In the previous example, we had the increment equal to one. The example 3 below shows how to loop though a dynamically defined range from 5 to 10 with the increment equal to 2. As in the previous examples, the for loop is used:

s=5
e=10
for i in $( seq ${s} 2 ${e} ); do echo ${i}; done
Output:
5
7
9

The final example 4 shows how to loop through a dynamically defined range, with start and length specified:

s=5
l=5
for i in $( seq ${s} $((${s} + ${l})) ); do echo ${i}; done
Output:
5
6
7
8
9
10