Bash scripting is a powerful tool that enables users to automate tasks and streamline workflows in Unix-based operating systems, such as Linux and macOS.
It can be used for a variety of purposes, including system administration, web development, data analysis, and more.
Here’s a quick overview from Fireship.io.
Components
Commands
Consist of a series of commands that are executed one after the other.
These commands can be standard Linux commands or custom commands written specifically for the script.
|
|
Variables
Use variables to store and manipulate data.
Variables can be assigned values, used in arithmetic and string operations, and passed as arguments to commands.
|
|
Control Structures
You can use control structures like if-else statements, loops, and functions to control the flow of execution.
These structures allow scripts to make decisions, repeat tasks, and perform complex operations.
|
|
Input and Output
Bash scripts can read input from various sources, including standard input, command-line arguments, and files.
They can also write output to standard output, files, and other destinations.
|
|
Error Handling
Errors and exceptions using error codes, traps, and logging.
They can also send email notifications and perform other actions in response to errors.
|
|
Regular Expressions (RegEx)
You can use regular expressions to perform pattern matching and text manipulation.
Regular expressions are a powerful tool for searching and replacing text within a script.
You can check out RegExr to learn more about how they work.
|
|
Functions
Define functions to encapsulate and reuse code.
Functions can take arguments, return values, and be used to perform complex tasks.
|
|
Get Started
For Basic Systems Administration
In this post, we’ll explore some of use cases for bash scripting and provide some examples that could be of use for you and your environment.
Performing Updates
We know updates are definitely important, so why not automate them in some way.
Create a auto-updates.sh
script and add the following:
|
|
Make Executable
|
|
You can also add this script to the crontab to automate your updates for your system.
Renaming Files
Renaming files can be a tedious and time-consuming task, especially when you have a large number of files to rename.
We could make it easier for ourselves by creating a script to automate this for us.
The basic command to rename files in Bash is mv
.
To rename a file named old_name.txt
to new_name.txt
, you can use the mv
command as below:
|
|
Renaming Multiple Files
If you want to rename multiple files at once, you can use a Bash script to automate the process.
Here is an example of how to rename all files in a directory with the .txt
extension:
|
|
This script will add the prefix new_
to the beginning of each file name with the .txt
extension.
Moving Files
Moving files is another task that can be automated with Bash scripting.
The mv
command can also be used to move files from one directory to another.
Here is an example of how to move a file named file.txt
from the current directory to the directory /home/user/documents/
:
|
|
This command will move the file file.txt
to the directory /home/user/documents/
.
Moving Multiple Files
To move multiple files at once, you can use a Bash script.
Here is an example of how to move all files in a directory with the .txt
extension to a new directory:
|
|
Performing Backups
|
|
This should perform a backup with tar
of the /etc
, /home
, and boot
directories to the specified directory
(in this case/backup
). Which could then be transferred to another machine once the backup is finished.
Other Use Cases
Web Development
Bash scripts are also useful for web developers who need to automate repetitive tasks such as deploying code, running tests, and building websites.
For example, a web developer can use a bash script to automate the process of deploying code to a production server.
|
|
Data Analysis
Bash scripting is also useful for parsing fairly large amounts of data, and automating tasks such as data cleaning, data transformation, and data visualization.
For example, you can use a bash script to clean a large CSV file and generate a summary report.
The script can contain commands that remove duplicates, filter rows, and aggregate data.
You’ll need the csvkit
package which can be installed with apt install
.
|
|
Docker
Quickly Install Docker
|
|
Cron
cron
is a utility program that allows users to schedule commands or scripts to run automatically at specified intervals in Linux-based operating systems.
The name “cron” comes from the Greek word “chronos”, which means “time”. The cron daemon is a background process that runs continuously and checks the crontab files for any scheduled jobs to run.
Adding Items to the Cron
|
|
If this is the first time you’re editing your crontab file, the system may ask you to choose an editor.
In the editor, add a new line for each command or script you want to schedule. The format of the line is as follows:
|
|
The asterisks represent the timing specification for the command, which defines when it should be executed.
For example, if you want a command to run every day at midnight, you would use the following line:
|
|
The cron daemon will automatically read the updated crontab file and start executing the scheduled commands at the specified intervals.
You can verify that your new items have been added to your crontab file by typing the following command:
|
|
Check out this helpful tool for editing your cron schedule expressions.
Add Scripts to Cron
|
|
If you want to redirect stdout
and errors to a file, you can modify the cron command like this:
|
|
Automating Backups
You can utilize scripts and cron
to perform backups, send them off to a remote server, and send a notification when they are done.
Example:
|
|
Snapshots with Timeshift
Timeshift is a free and open-source backup/restore utility for Linux systems.
It creates snapshots of the file system, allowing users to restore their system to a previous state if needed. Timeshift can be run manually or scheduled to run automatically using cron.
Snapshots can be stored locally or remotely, and users can choose the number of snapshots to keep and the frequency of snapshots.
You can create a bash script for defining how you would like timeshift to run, make sure to include sudo
when running:
|
|
You can then add this entry to your crontab to have cron run it every 3 days at 1am, or after your backups are done.
|
|
If you would like to simply add it to cron
manually, you can simply add the following:
Make sure to specify the <drive>
under --backup-device
.
|
|
Learn More
Make sure to check out the official Bash manual and other awesome guides like The Linux Documentation Project’s Beginner and Advanced Bash Scripting Guide, GreyCat’s BashGuide, and commandlinefu.
Conclusion
Although Bash is useful for automating tasks on a single host, if you wish to replicate this and multiply it across a multitude of hosts, you should take a look at my other Ansible post, where we take this to another level.
In conclusion, bash scripting is a powerful tool that enables users to automate tasks and streamline workflows in Unix-based operating systems.
By writing scripts, you can save time, reduce errors, and improve productivity.
Learn More
- Official GNU Bash Manual
- learnshell.org
- BashGuide
- TLDP
- MrTutorize YouTube Series
- Code Academy
- Devhints.io Cheat Sheet
- BashHackers