What is Bash Scripting?
Everything that may be executed as a command and placed into a shell script is permitted. The terminal either starts a new session or inserts the script into the current one for execution. Commands are often written in plain text.
Any command that can be run from the terminal can be included in a Bash script. A Bash script is a text file that contains a series of commands to be performed at the terminal.
An interpreter is an application or program that can translate and execute code written in a high-level programming language.
announces the intercept path. It must be added to the first line of the script.
No spaces are used in the shebang. Script execution is done with ./<script name>, <script name>, or bash<script name>.
A script must have executable permission to run.
The shell interpreter checks for an alias when a command is used.
To set up a persistent alias, edit the ~/.bashrc file.
The Linux system has a hierarchy of commands. If no alias is found, it will hunt for a function. And no function is found, it will try for a built-in command.
There is no built-in command. It will look in the PATH for a suitable function.
Variables are created with value assignments (variable = value). No spaces are used in the command. To call a variable in the script, use the prefix $<variable>.
Variables can have their values set in a variety of methods. The most popular ways are to set the value directly and to set the value as a result of command or program processing.
Bash checks for variable names before interpreting or running each line of our script. It substitutes the variable character with the value for each variable it has identified. Then it executes that line of code and repeats the process on the next line.
Script Input & Output
Read and Echo
Accept user input and store it to a variable.
The text following the word ‘echo’ is printed on the screen.
The read command takes a single sentence of input from the user. It puts a new line at the end of the previous one.
Using the –ep option, read creates a message from the user without requiring the first echo.
The variable ‘$(command)’ is saved as the command output. When a command contains more than two words, use a backtick (‘). Semicolons can be used to separate commands (;).
The script will produce the current user name and a list of all objects in the directory.
If the first command succeeds, && will execute the second command. If the first command fails, || will perform the second. | will route the first command’s stdout to the second command. Other command separators can be used as well.
If the conditions are met, the response will be true or false. Logical operators can be combined on a single line using the AND symbol ‘&&.’ OR is represented by the symbol ‘||.’
!= Does not equal to
-lt less than (number)
-gt greater than (number)
-eq Equals (number)
<> Less than greater than (string)
If, Else, Then
‘if’ must have ‘fi’ at the end of the statement. When ‘if’ and ‘else’ are on the same line, use a semicolon. Use square brackets for mathematical terms or string comparisons.
elif is a combination of else and if. To use elif, you must check for a condition. Elif tries to run when ‘if’ falls. ‘if’ ‘else’ exists, it will be the last condition checked.
A loop statement repeats a task. The “i” in the loop command is a variable that represents values in a range, like (1..255).
After the ‘for’ parameter in a loop is defined, the action is specified. A loop can be created either with “for” or “while.”
The ‘do’ parameter defines the action to perform if the condition is true. The ‘do’ action follows the ‘for’ parameter. ‘done’ closes the action’s specification.
A loop statement repeats a task. In the example on the right, each iteration will print the value of x and add 1 to the value.
Each time an iteration begins, the condition will be checked to see if it’s true. A loop can be created either with “for” or “while.”
Every command has an exit status code. The exit status syntax is “echo$?” and is run from the terminal window. A successful command output would be 0.
The exit code can be tested by adding it as a line in the script or as a CLI command. In the example on the right, ‘$?’ represents the exit code.
0 is the response code for a successful statement. If a statement fails, the status code will vary in accordance with the error code.
Let is the built-in command used to evaluate arithmetic expressions. It converts a variable to arithmetic expressions.
The “let” command does not require spaces. If space is needed in the expressions, it should be placed within quotation marks.
Arithmetic can be used to express calculations.
Using a double plus sign before or after the variable increments the value by 1. Variables are remembered by their place in the flow. The last variable that is calculated will be the final value.
In the following example, the output comes from 4 as the NUM variable in each of the equations.
A simple expression will calculate the sum and print the stdout. $SUM is saved as a variable and can be reused in the script.
In the following example, the output ($sum) will come to 5. Remember that double parentheses can be used for variables that include two expressions.
Zip & Unzip
Zip [options] file_name.zip> file.txt> [file2> [file3>]..]
After installation, the zip binary is located in the Debian /bin directory and can be called using the zip command.
Options can be added to the command. The ‘-d’ flag deletes the file during the unzipping process. The ‘-u’ flag updates the compression.
Zip is not installed by default in the Debian distribution. The zip command will compress the specified files. A list of files that were added will be displayed at the end of the command.
$ zip compress.zip file1.txt file2.txt file3.txt file4.txt
By default, files will be decompressed to the same directory unless specified using the ‘-d’ flag.
Unzipping compressed archives is done the same way as zipping them. The zipped folder must be specified. To export the zipped content to a different folder, use the “-d” flag.
$ unzip compress.zip -d /tmp/
Tar is typically used by Linux system administrators to back up data. It creates archive files that can be moved easily from disk to disk. A tar archive is created using: tar -cvf <archive_name. <directory>
Adding a ‘z’ will create a Gzip compressed tar archive. -zcvf means the following.
$ tar -cvf backupSettings.tar.gz /etc/
$ tar -zcvf backupSettings.tar.gz /etc/
z-compress using Gzip
c-create a new archive.
v- show a list of processed files.
f- specify the archive name.
Hashing is the process of generating a value from a string of text using a mathematical algorithm. They are cryptographically secure by the one-way algorithm.
Hashes are used for almost any type of digital content, including text, documents, images, and more. Linux has a built-in command for checksum generation.
The most popular encryption utility in Linux is md5sum. MD5 is no longer a secure hashing algorithm.
Tools that are the most used are:
Cron & Cron Table
Crontab is a tool that stores scheduled tasks for Cron’s execution. Cron tasks can only run for users who created them, with the exception of root user.
Task settings are configured using commands. Cron can be edited (as a file) using any text editor.
Important Cron flags include:
e- edits the file
l- lists task
r- remove tasks
Remember, when Cron is started for the first time, you have to mention the text editor.
- Use external scripts from trusted sources.
- Always use the proper permissions in the script that Cron runs.
- You can use whitelisted users.
- Disable root access.
- Avoid using tasks that require passwords.
- Run the task as a user using only the required privileges.
- The Chain commands fewer processes and exposure.
- Don’t allow unusual tasks.