Skip to main content

Command Palette

Search for a command to run...

Shell Scripting Essentials

Updated
2 min read
Shell Scripting Essentials

Shell scripting is a powerful way to automate tasks in a Unix/Linux environment. This blog will cover the fundamental concepts of writing and running scripts, understanding the shebang line, commenting code, using variables, and performing basic arithmetic operations.

1. Writing and Running Scripts (.sh Files)

To create a shell script, you can use any text editor like nano, vim, or gedit.

Example:

# Create a new script file
nano myscript.sh

Inside myscript.sh, you can write your script. To run your script, you need to make it executable and then execute it.

Make the script executable:

chmod +x myscript.sh

Run the script:

./myscript.sh

2. Understanding Shebang (#!)

The shebang (#!) is the first line in a script that tells the system which interpreter to use to execute the script. For example, to use Bash as the interpreter, you would start your script with:

#!/bin/bash

This line ensures that the script is run with the Bash shell.

3. Commenting Code for Clarity

Comments are essential for making your scripts understandable. In shell scripts, comments begin with the # symbol. Anything following # on that line will be ignored by the interpreter.

Example:

# This is a comment
echo "Hello World!"  # This prints a greeting

4. Using Variables to Store and Reuse Data

Variables allow you to store data for reuse throughout your script. In shell scripting, you don’t need to declare a variable before using it. Simply assign a value without spaces around the equal sign.

Example:

name="Dinesh"
echo "Hello, $name!"  # Output: Hello, Dinesh!

Output:

5. Basic Arithmetic Operations

You can perform basic arithmetic operations in shell scripts using the expr command or the $((...)) syntax.

Using expr:

result=$(expr 5 + 3)  # Adds 5 and 3
echo "The result is: $result"  # Output: The result is: 8

Output:

Using $((...)):

result=$((5 + 3))  # Adds 5 and 3
echo "The result is: $result"  # Output: The result is: 8

Output:

Supported Operations:

  • Addition: +

  • Subtraction: -

  • Multiplication: *

  • Division: /

  • Modulus: %

Conclusion

Shell scripting is a vital skill for automating tasks and managing systems efficiently. By mastering these basics—writing and running scripts, understanding shebang, commenting, using variables, and performing arithmetic—you will be well on your way to creating powerful scripts.

Experiment with these concepts and gradually build more complex scripts as you become comfortable. Happy scripting!

More from this blog

Dinesh's Blog

104 posts