Understand Linux Shell and Basic Shell Scripting Tips – Part I

The Linux shell, or command-line interface, is a powerful program that enables users to interact with the operating system via text-based commands.

Understanding the basics of the Linux shell and shell scripting can greatly enhance your efficiency and control over your system.

In this guide, we’ll explore key concepts and provide tips for both beginners and those looking to delve into basic shell scripting.

Understanding Linux Shell

The shell is a command-line program that interprets user commands and translates them into actions that the operating system can perform. It acts as an intermediary between the user and the Linux kernel, enabling users to control and manipulate the system through commands.

  • Shell – A command-line interpreter that connects a user to the operating system, allowing the execution of commands or the creation of text scripts.
  • Process – Any task that a user runs in the system is called a process. A process is a bit more complex than just a task.
  • File – A file resides on the hard disk (HDD) and contains data owned by a user.
  • X-Windows (X11) – A mode of Linux where the screen (monitor) can be split into small “parts” called windows, allowing a user to perform several tasks simultaneously, switch from one task to another easily, and view graphics in a visually appealing way.
  • Terminal – A monitor that has only the capability of displaying text, without graphics or with very basic graphics.
  • Session – The time between logging on and logging out of the system.

Types of Linux Shells

Linux supports several types of shells, with Bash (Bourne Again Shell) being the most prevalent. Other notable shells include Zsh (Z Shell), Fish, and Dash.

Each shell has its features and syntax, catering to different user preferences and needs.

  • Bash – It is the default shell for most Linux distributions and is widely used due to its versatility and powerful scripting capabilities.
  • Zsh – It is known for its enhanced features and improved user interface. It incorporates features from other shells, including Bash and Korn.
  • Fish – It is designed to be user-friendly with a focus on simplicity and discoverability by providing syntax highlighting and auto-suggestions for commands.
  • Dash – It is a lightweight shell designed for efficiency that is often used as the default system shell on minimalistic Linux distributions.
  • Ksh – It is a powerful shell with a focus on both interactive use and scripting that incorporates features from the Bourne shell (sh) and the C shell (csh).
  • Csh – It is designed with a syntax resembling the C programming language, which is known for its interactive features and scripting capabilities.

Basic Commands

There are thousands of commands for command-line users. How about remembering all of them? Hmm! Simply, you cannot. The real power of a computer is to simplify your work. To ease your work, you need to automate processes, and hence, you need scripts.

Scripts are collections of commands stored in a file. The shell can read this file and act on the commands as if they were typed at the keyboard. The shell also provides a variety of useful programming features to make scripts truly powerful.

Basics of Shell Programming

Shell programming involves creating scripts that utilize the capabilities of a shell, such as Bash, to automate tasks and execute commands. Understanding the basics of shell programming is essential for efficient and customized usage of the command-line interface.

Shebang (#!) Line

Every shell script begins with a shebang line specifying the interpreter to execute the script.

For Bash scripts, it is commonly #!/bin/bash.

#!/bin/bash

Comments

Use # to add comments to your script. Comments are for human readability and are ignored by the shell.

# This is a comment

Variables

Variables store data in a script. Use the assignment operator (=) without spaces to assign values to variables.

greeting="Hello, Shell!"

User Input

Use the read command to obtain user input during script execution.

read -p "Enter your name: " username

Echo

The echo command is used to print output to the terminal, which is often used for displaying messages or variable values.

echo "Welcome, $username!"

Conditional Statements

Use if, elif, and else for decision-making in scripts.

if [ condition ]; then
  # code to execute if the condition is true
else
  # code to execute if the condition is false
fi

Loops

Use for and while loops for repetitive execution of commands.

for i in {1..5}; do
  # code to repeat five times
done

Functions

Encapsulate code into functions for modularity and reusability.

function greet {
  echo "Hello, $1!"
}
greet "John"

Exit Status

Commands return an exit status. Use $? to check if the last command was successful (exit status 0) or encountered an error.

if [ $? -eq 0 ]; then
  echo "Command executed successfully."
else
  echo "Error during command execution."
fi

File Permissions

When dealing with sensitive operations in scripts, use the chmod command to set appropriate permissions on the file.

chmod +x myscript.sh

About Shell Script

A shell script is simply a text file with a ".sh" extension that has executable permissions.

Here are some tips to guide you through the process of writing and executing a script:

  • Begin your script with a shebang line (#!/bin/bash) to specify the interpreter.
  • Add comments to explain the purpose of your script, especially for complex or lengthy code segments.
  • Use the echo command to print the “Hello, World!” message to the terminal.
  • Before execution, ensure your script has the necessary permissions using the chmod command, e.g., chmod +x script.sh.

“This is how your first shell script looks.”

#!/bin/bash
# My first script

echo "Hello World!"

Save the above lines on a text file, make it executable, and run it, as described above.

Hello World Shell Script
Hello World Shell Script

Writing Second Script

Alright, it’s time to move on to the next script, which will display your ‘username‘ and list the currently running processes.

#! /bin/bash
echo "Hello $USER"
echo "Hey i am" $USER "and will be telling you about the current processes"
echo "Running processes List"
ps
List Running Processes
List Running Processes

Was this cool? Writing a script is as simple as conceiving an idea and composing a sequence of commands. However, there are some limitations. Shell scripts excel at concise filesystem operations and scripting the integration of existing functionality through filters and command-line tools via pipes.

When your requirements extend beyond, be it in functionality, robustness, performance, efficiency, etc., then transitioning to a more full-featured language is advisable.

If you are already familiar with C/Perl/Python or any other programming language, acquiring proficiency in a scripting language shouldn’t be too challenging.

Writing Third Script

Moving on, let’s write our third and final script for this article. This script functions as an interactive script. Why not try executing this simple yet interactive script yourself and share your experience with us?

#! /bin/bash
echo "Hey what's Your First Name?";
read a;
echo "welcome Mr./Mrs. $a, would you like to tell us, Your Last Name";
read b;
echo "Thanks Mr./Mrs. $a $b for telling us your name";
echo "*******************"
echo "Mr./Mrs. $b, it's time to say you good bye"
Interactive Script
Interactive Script

Well, this is not the end. We tried to introduce you to the basics of scripting. In our future articles, we will delve deeper into the topic of scripting languages – a vast and ever-evolving field—to provide a more comprehensive understanding.

Your valuable thoughts in the comments are highly appreciated. Please like and share to help us reach a wider audience. Until then, relax, stay connected, and stay tuned.

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.