Bash-scripts
A collection of Bash scripts for automating routine tasks and streamlining your workflow. From simple file renaming to more complex deployments, these Bash scripts have you covered.

About Bash
Bash (Bourne Again SHell) is an essential component of Unix-like operating systems. It's a powerful scripting language and command interpreter that has evolved from its predecessors in the Unix world. Here's an overview:
Historical Background
The origin of scripting languages can be traced back to their initial role as enhancements to command interpreters within operating systems. These early scripting tools were designed to automate repetitive tasks, streamline workflows, and improve the efficiency of system administration.
One of the first significant developments in this area was the creation of the Bourne Shell (sh) in the 1970s. Developed by Stephen Bourne at AT&T’s Bell Labs, it became the standard command interpreter for Unix systems, setting the foundation for future shell environments with its powerful scripting capabilities and control structures.
Building upon the Bourne Shell’s framework, the Bash (Bourne Again SHell) was introduced in 1989 as part of the GNU Project. Designed as a free software replacement for the Bourne Shell, Bash incorporated numerous enhancements, including improved scripting features, better error handling, and additional programming constructs. Today, Bash is the most widely used Unix shell, favored for its versatility and robust functionality across Unix-like operating systems, including Linux and macOS.
In addition to Bash, several other Unix shells have been developed over time, each offering unique features tailored to different user preferences and system requirements. These include the C Shell (csh), which introduced C-like syntax; the TENEX C Shell (tcsh), an enhanced version of csh with improved interactive features; the lightweight Dash (Debian Almquist Shell), optimized for speed and minimal resource usage; the Korn Shell (ksh), known for its advanced scripting capabilities and compatibility with both Bourne and C shell syntax; and the highly customizable Z Shell (zsh), which combines features from multiple shells and offers extensive configurability for power users.
Purpose of Shell Scripts
- Shell scripts are invaluable for repetitive command sequences by automating tasks, particularly in programming and server administration, especially for file and directory operations, text processing, and network configuration.
- Bash and other scripting languages incorporate features like variables, conditional statements, loops, arrays, and functions, providing more sophisticated control flow.
- The true strength of shell scripting lies in its ability to utilize the vast array of Unix commands.
- When scripts become overly complex for Bash, transitioning to more powerful languages like Python is advisable.
- Bash scripts can be used to integrate or 'glue' together complex scripts written in languages such as Python.
Limitations of Bash
- Bash is not well-suited for developing complex applications.
- It's not designed for building GUI applications.
- Bash scripts may not be portable across different operating systems without modification.
- It's less efficient for complex calculations compared to languages like Python.
- Bash has limitations in handling advanced network programming tasks.
"Hello World" in Bash
A basic example of a Bash script is the famous "Hello World". It demonstrates how to output text to the console.
#!/usr/bin/env bash
echo "Hello world"
Executing a script
To execute a Bash script, you need to make it executable and then run it from the terminal. Here's how you can do it:
chmod u+x filename.sh # Make the script executable
./filename.sh # Execute the script
The Shebang
The shebang (#!) line at the beginning of a script is crucial for defining the script's interpreter. It's more than just a convention; it's an essential aspect of script execution in Unix-like systems. Here's an expanded view:
Example Shebang for Bash:
#!/usr/bin/env bash
Execution Contexts
- When a script is executed directly from a terminal, the shebang's specified interpreter is used. Example:
./filename.sh
- If the script is invoked from another shell script, the parent script's interpreter is used, and the shebang in the child script is ignored.
- When a script is executed with an explicit interpreter command (like
bash ./filename.sh), the shebang line is bypassed.
Shebang in Other Languages
- The shebang is not limited to Bash scripts, as it is used in various scripting languages to specify their respective interpreters.
- An example of a shebang for Perl is
#!/usr/bin/env perl.
- An example of a shebang for Python is
#!/usr/bin/env python3.
Variables
Variables in Bash are not just simple placeholders for values; they can be used in more complex ways:
- To assign a value to a variable, you use
var="Test".
- To retrieve the value stored in a variable, you use
$var or ${var}.
- Bash supports explicitly defining variable types such as integers and arrays.
declare -i var # 'var' is an integer
declare -a arr # 'arr' is an array
declare -r var2=5 # 'var2' is a read-only variable
- Bash allows storing the output of a command in a variable using command substitution, like
var=$(whoami).
- Environment variables are global and can be accessed by any process running in the shell session, such as
PATH, HOME, and USER.
- To make a variable available to child processes, it needs to be exported using
export var.
- Variables in functions can be made local to avoid affecting the global scope.
function myFunc() {
local localVar="value"
}
Command Line Arguments in Bash
Command line arguments in Bash scripts are accessed using special variables:
$1 represents the first argument passed to the script.
$@ is an array-like construct that holds all command line arguments.
$# gives the number of command line arguments passed.
$? contains the exit status of the last executed command.
If Statements in Bash
If statements in Bash are crucial for decision-making processes based on conditions.
Basic Syntax:
if [ condition ]; then
# commands
fi
- Integer Comparisons: Use specific operators for comparing integer values.
if [ $i -eq 10 ]; then echo True; fi # Integer comparison
- String Comparisons: Strings are compared differently from integers.
if [ "$name" == "10" ]; then echo True; fi # String comparison
Operators for Integer Comparison
| Operator |
Description |
-eq |
equal |
-ne |
not equal |
-gt |
greater than |
-ge |
greater than or equal to |
-lt |
less than |
-le |
less than or equal to |
Operators for String Comparison
| Operator |
Description |
== |
equal |
!= |
not equal |
> |
greater than |
< |
less than |
-n |
string is not null |
-z |
string is null |
Single vs Double Square Brackets:
- Single brackets
[ ] are compatible with POSIX shell and suitable for basic tests.
- Double brackets
[[ ]] are used in Bash and other shells like Zsh and Ksh to offer enhanced test constructs.
- They support logical operators like
|| and regex matching with =~.
- They do not perform word splitting or filename expansion.
Filename Expansion Example:
- No Globbing with Double Brackets:
if [[ -f *.csv ]]; then echo True; fi # Checks for a file named "*.csv"
- Globbing with Single Brackets:
if [ -f *.csv ]; then echo True; fi # Performs filename expansion
Loops
Loops are used in Bash to execute a series of commands multiple times. There are several types of loops, each serving different purposes.
For Loop
The for loop is used to iterate over a list of items or a range of values.
Syntax:
for var in list; do
# commands
done
Example with a List:
for i in 1 2 3; do
echo $i
done
Example with a Range:
for i in {1..3}; do
echo $i
done
Example with Command Output:
for file in $(ls); do
echo $file
done
While Loop
The while loop executes as long as a specified condition is true.
Syntax:
while [ condition ]; do
# commands
done
Example:
i=1
while [ $i -le 3 ]; do
echo $i
((i++))
done
Until Loop
The until loop is similar to the while loop but runs until a condition becomes true.
Syntax:
until [ condition ]; do
# commands
done
Example:
i=1
until [ $i -gt 3 ]; do
echo $i
((i++))
done
Loop Control: Break and Continue
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
break
fi
echo $i
done
- continue: Skips the rest of the loop iteration and continues with the next one.
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
continue
fi
echo $i
done
C-Style For Loop
Bash also supports a C-style syntax for for loops, which provides more control over the iteration process.
Syntax:
for (( initialisation; condition; increment )); do
# commands
done
Example:
for (( i=1; i<=3; i++ )); do
echo $i
done
Arrays
An array is a variable that holds an ordered list of values. The values are separated by spaces. The following example creates an array named array and assigns the values 1, 2, 3, 4, 5 to it:
array=(1 2 3 4 5)
It is possible to create an array with specified element indices:
array=([3]='elem_a' [4]='elem_b')
To insert an elementat (e.g. 'abc') at a given index (e.g. 2) in the array, use the following syntax:
array=("${array[@]:0:2}" 'new' "${array[@]:2}")
To iterate over the elements of an array, use the following syntax:
items=('item_1' 'item_2' 'item_3' 'item_4')
for item in "${items[@]}"; do
echo "$item"
done
# => item_1
# => item_2
# => item_3
# => item_4
It is often useful to print the elements of an array on a single line. The following code will print the elements of the array on a single line:
echo "${array[*]}"
Functions
Functions are used to group a sequence of commands into a single unit. They are used to perform repetitive tasks. Functions can be called from anywhere in the script. The following example creates a function named hello_world that prints the string Hello World to the standard output (stdout):
hello_world()
{
echo "Hello World!"
}
To call the function, use the following syntax:
hello_world
The above function does not take any arguments and does not explicitly return a value. It is possible to pass any number of arguments to the function. It is also possible to return a value from the function, but only an integer from range [0,255] is allowed.
Here is a complete example of a script that defines and uses a function to sum two numbers:
#!/usr/bin/env bash
sum_two()
{
return $(($1 + $2))
}
sum_two 5 3
echo $?
Pipes
The pipe is used to pass the output of one command as input to the next:
ps -x | grep chromium
Redirections
But what if you'd want to save the results to a file? Bash has a redirect operator > that may be used to control where the output is delivered.
some_command > out.log # Redirect stdout to out.log
some_command 2> err.log # Redirect stderr to file err.log
some_command 2>&1 # Redirect stderr to stdout
some_command 1>/dev/null 2>&1 # Silence both stdout and stderr
Complete summary:
| Syntax |
StdOut visibility |
StdErr visibility |
StdOut in file |
StdErr in file |
existing file |
> |
no |
yes |
yes |
no |
overwrite |
>> |
no |
yes |
yes |
no |
append |
2> |
yes |
no |
no |
yes |
overwrite |
2>> |
yes |
no |
no |
yes |
append |
&> |
no |
no |
yes |
yes |
overwrite |
&>> |
no |
no |
yes |
yes |
append |
tee |
yes |
yes |
yes |
no |
overwrite |
tee -a |
yes |
yes |
yes |
no |
append |
n.e. (*) |
yes |
yes |
no |
yes |
overwrite |
n.e. (*) |
yes |
yes |
no |
yes |
append |
|& tee |
yes |
yes |
yes |
yes |
overwrite |