Bash script introduction

Time:2022-2-17

[note] this article is translated from:An Introduction to Bash Scripting
Bash script introduction

Bash script introduction

Imagine yourself as a computer scientist, amateur or technical nerd? Then at some point, you will or should consider using bash scripts in your digital workspace.

Bash (Bourne Again Shell)“) is an interpreter responsible for processing commands on the command line of UNIX system. It isFree software written by Brian FoxFree software released in 1989 as a substitute for SH (Bourne shell). Bash is used by developers, data scientists, system administrators, network engineers and anyone else who relies heavily on the UNIX operating system in their daily work. In general, bash scripts are used to automate the day-to-day remedial tasks that computer scientists may undertake. In short, a shell script is simply a series of commands stored in a file, such as a list.

You canLinuxBash can be used on MacOS machines and even on Windows 10 machines through the windows subsystem for Linux. Bash usually runs in a text window where users can type commands to let the computer perform operations. The language can also be used to read and execute commands from files, called shell scripts. Shell script itself is a programming language. Like any other language, Bash is a tool that can be used in many ways.

If you have seen a machine running a Linux operating system (or UNIX like environment) before, you may also have seen a terminal console. The terminal is a way for the user to interact with the shell interpreter using some commands. such ascdNavigate to the file directory,lsLists the files in the current directory, andnanoCommands such as editing files.

Bash script introduction

Use bash code in the terminal, which will be run by bash interpreter.lsSuch commands are located in/binBinary executable in directory. When the shell receives the command (when you type it in the terminal and press enter), it executeslsFile and lists the files in the current directory for the user. Use commandls /binExecute binary with path / bin as optionls, list/binFiles in the directory. implementls -alWill run with flag-aand-lAs an optionlsCommand that lists all files and directories in the current directory path and details about these items.

touchIs another such binary executable file that users can use in the terminal. The output of this command is a new file with the name entered by the user as an option. For example, users can writetouch hello.txt, the output will be a filehello.txt

How to run multiple bash commands

To run multipleBashCommands and let them execute at once. Users can save these commands in a single file for execution in bash. Assuming you work in a UNIX / Unix like environment, let’s consider what we discussed earlier.

After opening the command terminal, first use your favorite text editor, such asnanoorvi。 write in:

nano make_a_file.txt

Then, write the following:

#create a file
touch hello.txt

#list files from this directory
ls -al

Save and exit the file and run the new script using one of the following command syntax:

sh make_a_file.txt

or

./make_a_file.txt

or

bash make_a_file.txt

If there is an error executing the file, continue to set the executable permissions for the script file you just wrote by entering the following:

chmod +x hello.sh

If you followed this example, you have just created a file that contains multiple bash commands. The bash interpreter will run the commands sequentially and ignore the lines that # begin with hash symbols because they are comments. Running this file will produce a terminal output of the file list, which will contain ahello.txtNo, not before.

Typically, a bash script file is created to contain.shThe format of the extension is saved, which indicates that the file is a shell script. However, when the file starts with “she Bang” or “hashbang”, we can execute it like a binary file.

When creating scripts, we should consider that each binary SHELL file starts with the commonly known “she Bang” (also known as sh bang or hashbang). This is the beginning of the script title, and the first line of code indicates which shell you will use. When making scripts, we have a variety of options, includingshell (sh)C ShellZ ShellWait. In this case, we will continue to use bash to meet our scripting needs. She Bang is a set of symbols at the beginning of the script“#”and“!”。 We know that a pound sign (#) indicates that a line is a comment. However, with she bang, the program interpreter of UNIX like systems parses the rest of the first line into interpreter instructions. In this case, when writing#!/bin/bashThe hash symbol and exclamation mark are used as indicators of the program loader to indicate that it uses the/bin/bashBash shell program for directory.

How to create variables in Bash

Like most other UNIX shells, bash has variables, pipes, file name wildcards, here documents, command substitution, and control flow. Bash also supports alternation (which is shared with the C shell), command line completion, and signal processing and basic debugging. With these features, it is not surprising that bash has become the default command interpreter for UNIX and UNIX like systems.

Like other programming languages, we can declare variables when scripting with bash. However, unlike other languages, bash does not require keywords to declare variables or assign data types to them. Bash has no type system and only saves variables as string values. But BashsureAutomatically converts variables to appropriate types based on certain operations, such as arithmetic operations. To write a variable and fill it with a value, use theVARIABLE=VALUEWrite the content in the format to ensure that there are no spaces. The following is an example of how to create variables in Bash:

#!/bin/bash

#write a variable
NAME=“William”

#use that variable
echo “Hello $NAME”

The user can also fill in variables through user input:

#!/bin/bash

echo “Hello $1, that is a $2 name”

In the terminal:

~$bash name.sh “William” “great”
Hello William, that is a great name

You can also usereadCommands such as use user input variables at run time:

#!/bin/bash

echo “What is your name?”

read name

echo “Hello $name”

In the terminal:

~$bash name.sh
What is your name?
~$William
Hello William

If statement in Bash

We can also implement for additional functionsifsentence.

#!/bin/bash

echo “Who is there?”

read name

if [ $name ]
echo “Hello $name”
else
 echo “Must’ve been my imagination”
fi

In the terminal:

~$bash name.sh
Who is there?
~$
Must’ve been my imagination

How to create a backup management script in Bash

Other items to consider include setting up backup management scripts. This can be a simple project that can be started and revisited later. With this, you can make a simple script to compress one or more files and folders using tar library and place them in the new backup directory of your choice. The following script is a basic backup script that creates a backup for the files that need to be backed up Zip files and mark them according to the creation date:

#!/bin/bash

#get the month, day, and year of the current date
TIME_OF_BACKUP=`date +%m-%d-%y`

#create a backup file using the current date in its name
DESTINATION=/path/[BACKUP FOLDER]-$TIME_OF_BACKUP.tar.gz

#the folder that contains the files that we want to backup
TARGET_FOLDER=/path/[TARGET FOLDER]

#create the backup
tar -cpzf $DESTINATION $TARGET_FOLDER

As a reward, you may want to add some complexity to this project and increase the level of automation by adding scheduled execution to the backup script. To do this, you can use the crontab program and the command library. If you need to install cron, make sure to update your current package library before continuing with cron installation.

sudo apt-get update
sudo apt-get install cron

After successful installation, you can continue to use the cron library to schedule script execution.

crontab -e

This will open/etc/crontabFile and allows you to write the following commands to schedule the execution of the script:

@weekly /path/backup_script.sh

I won’t discuss further what you can usecrontabWhat to do because it is not within the scope of this article.

summary

Through this getting started guide, you will know what Bash is, what scripts are, and what scripts are in bash. You can do many things with bash, and you don’t need to know much about programming, you can piece together different Linux applications and tools and make some useful things. Bash script is a very useful tool. I hope you can get inspiration from this article and automate your ideas.