Shell Scripting Basics: Your First Steps into Scripting

Last updated at: September 08, 2024
Written by: Abdul

Creating Your First Script

Let's dive right in and create your very first shell script. Follow these steps:

  1. Open your terminal or command prompt.
  2. Create a new file using a text editor. For example: nano myfirstscript.sh
  3. In the editor, type the following:
    #!/bin/bash
    echo "Hello, World!"
    
  4. Save the file and exit the editor.

Congratulations! You've just written your first shell script.

Understanding the Shebang

The first line of our script, #!/bin/bash, is called the "shebang" or "hashbang". It tells the system which interpreter to use to run the script. In this case, we're specifying the Bash shell.

File Permissions

Before we can run our script, we need to make it executable. Use the following command:

chmod +x myfirstscript.sh

This command gives the file execute permissions.

Running Scripts

To run your script, use one of these methods:

The first method uses the shebang to determine the interpreter, while the second explicitly uses Bash.

Comments and Basic Syntax

Comments in shell scripts start with a #. They're ignored by the shell and are used to explain your code. For example:

# This is a comment
echo "This will be printed" # This is an inline comment

Basic syntax rules:

A More Complex Example

Let's create a slightly more advanced script:

#!/bin/bash

# This script greets the user and tells them the current date

# Get the current user's name
username=$(whoami)

# Get the current date
current_date=$(date +"%Y-%m-%d")

# Print greeting and date
echo "Hello, $username!"
echo "Today's date is: $current_date"

This script introduces variables and command substitution, which we'll explore more in future articles.

Conclusion

You've now taken your first steps into the world of shell scripting! You've learned how to create, make executable, and run a script. You've also been introduced to comments, basic syntax, and a glimpse of more advanced concepts.

In our next article, we'll dive deeper into working with variables and user input. Keep practicing with simple scripts, and soon you'll be automating tasks like a pro!