3.3 Turning Commands into a Script

3.3 Turning Commands into a Script

Weight: 4

Description: Turning repetitive commands into simple scripts.

Key Knowledge Areas:

  • Basic shell scripting

  • Awareness of common text editors (vi and nano)

The following is a partial list of the used files, terms and utilities:

  • #! (shebang)

  • /bin/bash

  • Variables

  • Arguments

  • for loops

  • echo

  • Exit status

Introduction to Linux Shell and Shell Scripting

Like any modern operating system linux involves interacting with a shell, which interprets and executes user commands. this interaction typically happens through the terminal, where users type commands for the shell to process.

Before learning shell scripting, you must understand:

  • Kernel

  • Shell

  • Terminal

Kernel

The kernel is a computer program that is the core of a computer's operating system, with complete control over everything in the system. It manages the following resources of the Linux system:

  • File management

  • Process management

  • I/O management

  • Memory management

  • Device management etc.

Complete Linux system = Kernel + GNUsystem utilities and libraries + other management scripts + installation scripts.

Shell

A shell is a special user program that provides an interface for the user to use operating system services. Shell accepts human-readable commands from users and converts them into something which the kernel can understand. It is a command language interpreter that executes commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or starts the terminal.

Shell is broadly classified into two categories –

  • Command Line Shell

  • Graphical shell

Terminal

A program which is responsible for providing an interface to a user so that he/she can access the shell. It basically allows users to enter commands and see the output of those commands in a text-based interface. Large scripts that are written to automate and perform complex tasks are executed in the terminal. To access the terminal, simply search in search box "terminal" and double-click it.

Before start writing our first hello world! shell script , we need to know about linux text editors.

Linux Text Editors

For Linux users, text editors are essential tools that play a crucial role in various tasks, from coding and writing to system administration and configuration management. Linux offers a wide range of text editors, catering to different preferences and use cases. In this article, we just have a quick look at vi (vim) , nano text editors.

vi

Vi (pronounced "vee-eye") is one of the oldest yet most popular text editors for Linux and Unix-based systems.

  • It operates differently from modern editors because it uses multiple modes instead of direct typing.

  • Vi does not rely on a mouse — all operations are performed using keyboard shortcuts.

  • It is lightweight, fast, and available on almost all Unix and Linux systems by default.

  • Though it may seem difficult for beginners, it becomes extremely efficient once learned.

  • Many system administrators and developers prefer Vi for quick file edits directly from the terminal.

  • It’s a reliable choice for working on remote servers or systems with minimal resources.

What is Vim?

Most Linux distributions come with Vim pre-installed. However, if it's not available on your system, you can install it using your package manager. For instance:

Now vim will be installed on your system. Let's Start to use Vim

vim

You can open vim by running vim command on the terminal.

Modes in Vim:

One of the unique features of Vim is its modes. Vim has several modes, each serving a different purpose:

  1. Normal Mode: This is the default mode when you first open Vim. In this mode, you can navigate the file, delete text, copy text, and perform other commands.

  2. Insert Mode: This mode allows you to insert and edit text. To enter Insert Mode from Normal Mode, press `i`.

  3. Visual Mode: In this mode, you can visually select blocks of text. To enter Visual Mode from Normal Mode, press `v`.

  4. Command-Line Mode: This mode lets you enter Vim commands. To enter Command-Line Mode from Normal Mode, press `:`.

To open a file in vim editor just write the file name after the vim command in the terminal as follows:

Then the file will be opened.

Write into file :

In the previous step we have opened the file now, Let's write some content in to write data we need to go in insert mode. To go into write mode type i. As follows:

After going into insert mode you will see INSERT in the status bar. After that, we can write any data in it.

Navigating in Vim:

  • Moving the Cursor: Use the arrow keys or `h`, `j`, `k`, `l` keys to move left, down, up, and right respectively.

  • Jumping to the Beginning or End of a Line: Press `0` to jump to the beginning of a line and $ to jump to the end.

  • Jumping to a Specific Line: Type `:<line_number>` and press Enter to jump to a specific line.

text editing in vim:

Save and Exit:

We have written the data into a file now the task is to save and exit the file to do that first exit from insert mode by pressing the Esc key. To write a command first type semicolon ( : ) and then type the command wq! or x! (both do the same thing) And then hit ENTER.

Exit without saving the file:

To exit from the file without saving the file just use the command q! As follows

Vim also comes with its own tutorial. You can see this tutorial by command vimtutor into the terminal . vimtutor

nano

Nano is a simple, lightweight, and user-friendly text editor used in Linux and other Unix-based systems.

  • It offers a clean interface with on-screen keyboard shortcuts, making it easy to learn and use.

  • Provides basic editing features such as cut, copy, paste, undo, redo, and search/replace.

  • Supports syntax highlighting for various programming languages.

  • Allows users to edit multiple files simultaneously using multiple buffers.

  • Does not require switching modes like vi or vim, making it ideal for beginners.

  • Common shortcuts are displayed at the bottom of the screen (e.g., Ctrl + O to save, Ctrl + X to exit).

  • Suitable for both new users and experienced administrators who prefer quick edits in the terminal.

Emacs

GNU Emacs is a powerful and highly customizable text editor for Linux professionals created by Richard Stallman, the founder of the GNU project. It is designed to be versatile and has a wide range of built-in functions.

Emacs is used both as a command-line text editor and a GUI text editor. This dual functionality makes it suitable for many different users and use cases.

Gedit

Gedit is a text editor that comes with the GNOME desktop environment. The design emphasizes simplicity, so Gedit is a great editor for beginners.


Getting Started with Shell Scripting

In the world of DevOps and system administration, automating repetitive tasks is key to saving time and reducing errors. That’s where shell scripting comes in. It allows you to write a series of commands in a file and run them all at once, just like a program. Whether it is setting up servers, managing files, or deploying code shell scripts make it fast, consistent, and effortless.

Shell Script

A shell script is a file containing a series of commands for the shell to execute. The shell itself is a command-line interpreter (CLI), while a shell script is a saved list of instructions (usually with .sh extension) like myscript.sh.

Our first Hello world! bash script:

but wait , what is that first line?

shebang

The most common need for using shebang appears when we’re writing shell scripts.

The shebang is an interpreter directive used in Unix-like operating systems. It is a character sequence, #!, that constitutes the first line of a script. This line specifies the absolute path to the system interpreter (such as bash, python3, or perl) required to execute the commands within the script.

You will use a shebang to:

  • Tell the system what language a script is in (e.t., bash, python3, node).

  • Allow you to run a script directly (e.g., ./myscript.py) instead of typing the interpreter's name first (e.g., python3 myscript.py).

  • Make your scripts portable so they work on other people's computers.

How It Works: The Three Key Components

There are three distinct concepts that work together.

1. The Shebang (#!)

The name "shebang" comes from its two characters:

  • #: The "hash" or "sharp" symbol.

  • !: The "bang" or exclamation mark.

When you try to run a file, the Linux kernel opens it, sees the #! at the beginning, and knows it shouldn't run the file itself. Instead, it reads the rest of the line as a command to run, using the script as the input for that command.

2. The Path

The path is the part after the #!.

  • What it does: This directly tells the system to use the python3 program located in the /usr/bin folder.

  • Why it's bad: What if another user's python3 is in /usr/local/bin/python3? The script will fail.

3. The Executable Permission (chmod +x)

The shebang tells the system how to run the script, but the file's permissions tell the system if it's allowed to be run.

This is a separate and mandatory step.

  • chmod +x myscript.sh grants executable permission.

  • chmod -x myscript.sh removes executable permission.

and lets run our first Hello World! script:

Comments in bash scripting

Comments start with a # in bash scripting. This means that any line that begins with a # is a comment and will be ignored by the interpreter.

Comments are very helpful in documenting the code, and it is a good practice to add them to help others understand the code.These are examples of comments:

Variables and data types in Bash

Variables let you store data. You can use variables to read, access, and manipulate data throughout your script.

There are no data types in Bash. In Bash, a variable is capable of storing numeric values, individual characters, or strings of characters.

In Bash, you can use and set the variable values in the following ways:

  1. Assign the value directly:

  1. Assign the value based on the output obtained from a program or command, using command substitution. Note that $ is required to access an existing variable's value.

To access the variable value, append $ to the variable name.

Variable naming conventions

Input and output in Bash scripts

Gathering input

In this section, we'll discuss some methods to provide input to our scripts.

  1. Reading the user input and storing it in a variable

We can read the user input using the read command.

  1. Reading from a file

This code reads each line from a file named input.txt and prints it to the terminal. We'll study while loops later in this article.

  1. Command line arguments

In a bash script or function, $1 denotes the initial argument passed, $2 denotes the second argument passed, and so forth.

This script takes a name as a command-line argument and prints a personalized greeting.

arguments

One of the most essential aspects of Bash scripting is the ability to pass arguments to your scripts. This feature allows scripts to be flexible and dynamic, capable of handling various inputs and performing different actions based on those inputs.

When you pass arguments to a Bash script, they are stored in positional parameters, which are special variables:

  • $0 is the name of the script.

  • $1, $2, and so on represent the arguments passed to the script.

  • $# gives the number of arguments passed.

  • $@ and $* represent all the arguments passed.

Let’s create an example script.

Now, we’ll run this script using the following arguments:

Output:

In this example, the script prints the script’s name, the first and second arguments, the total number of arguments, and all arguments as a list.

Conditional statements (if/else)

Expressions that produce a boolean result, either true or false, are called conditions. There are several ways to evaluate conditions, including if, if-else, if-elif-else, and nested conditionals.

Syntax:

Let's see an example of a Bash script that uses if, if-else, and if-elif-else statements to determine if a user-inputted number is positive, negative, or zero:

The script first prompts the user to enter a number. Then, it uses an if statement to check if the number is greater than 0. If it is, the script outputs that the number is positive. If the number is not greater than 0, the script moves on to the next statement, which is an if-elif statement. Here, the script checks if the number is less than 0. If it is, the script outputs that the number is negative. Finally, if the number is neither greater than 0 nor less than 0, the script uses an else statement to output that the number is zero.

Looping and Branching in Bash

While loop

While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.

In the example below, (( i += 1 )) is the counter statement that increments the value of i. The loop will run exactly 10 times.

For loop

The for loop, just like the while loop, allows you to execute statements a specific number of times. Each loop differs in its syntax and usage.

In the example below, the loop will iterate 5 times.

Case statements

In Bash, case statements are used to compare a given value against a list of patterns and execute a block of code based on the first pattern that matches. The syntax for a case statement in Bash is as follows:

Here, "expression" is the value that we want to compare, and "pattern1", "pattern2", "pattern3", and so on are the patterns that we want to compare it against.

The double semicolon ";;" separates each block of code to execute for each pattern. The asterisk "*" represents the default case, which executes if none of the specified patterns match the expression.

Let's see an example.

In this example, since the value of "fruit" is "apple", the first pattern matches, and the block of code that echoes "This is a red fruit." is executed. If the value of "fruit" were instead "banana", the second pattern would match and the block of code that echoes "This is a yellow fruit." would execute, and so on. If the value of "fruit" does not match any of the specified patterns, the default case is executed, which echoes "Unknown fruit."

Check the exit code

When Bash encounters an error, it sets an exit code that indicates the nature of the error. You can check the exit code of the most recent command using the $? variable. A value of 0 indicates success, while any other value indicates an error.

Exist Status

Each Linux or Unix command returns a status when it terminates normally or abnormally. You can use value of exit status in the shell script to display an error message or run commands. For example, if tar command is unsuccessful, it returns a code which tells the shell script to send an e-mail to sysadmins.

You can use special shell variable called $? to get the exit status of the previously executed command.

What is the $? (dollar question mark) in Bash?

The $? (dollar question mark) is the exit status of the last task or executed command by bash. It is a particular reserved shell variable that you can use to find out if your last executed command failed or not.

example:

Notes:

  1. The exit status is an integer number.

  2. For the bash shell’s purposes, a command which exits with a zero (0) exit status has succeeded.

  3. A non-zero (1-255) exit status indicates failure.

  4. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126

  5. All of the Bash builtins return exit status of zero if they succeed and a non-zero status on failure.

We can also store exit code for other perposes:

That's all!

.

.

.


sources:

https://www.geeksforgeeks.org/linux-unix/introduction-linux-shell-shell-scripting/ https://www.geeksforgeeks.org/linux-unix/using-shebang-in-linux/ https://www.geeksforgeeks.org/linux-unix/linux-text-editors/ https://www.geeksforgeeks.org/linux-unix/basic-vi-commands/ https://www.geeksforgeeks.org/linux-unix/getting-started-with-vim-editor-in-linux/ https://phoenixnap.com/kb/best-linux-text-editors-for-coding

https://www.freecodecamp.org/news/bash-scripting-tutorial-linux-shell-script-and-command-line-for-beginners/ https://www.freecodecamp.org/news/bash-scripting-tutorial-linux-shell-script-and-command-line-for-beginners/ https://www.cyberciti.biz/faq/linux-bash-exit-status-set-exit-statusin-bash/ https://www.atlantic.net/vps-hosting/passing-arguments-to-bash-scripts-a-practical-guide/

Last updated