CodeGym /Courses /Docker SELF /Introduction to Bash Scripts: Syntax, Variables, Commands...

Introduction to Bash Scripts: Syntax, Variables, Commands

Docker SELF
Level 3 , Lesson 3
Available

Introduction to Bash Scripts: Syntax, Variables, Commands

1. What are bash scripts?

If you've ever thought: "Why do I need to repeat the same commands over and over again?", then congrats, you're ready for bash scripts! Bash scripts are a way to automate work in Linux by writing a sequence of commands in a single file. Bash (Bourne Again Shell) isn't just a shell, it's a Swiss Army knife for admins, programmers, and anyone who wants to make their system work for them.

Advantages of bash scripts

  • Time-saving: Write it once — run it eight times.
  • Task consistency: Scripts run the same way every time (well, if you wrote everything correctly).
  • Routine automation: Create customized commands for backups, resource monitoring, or file management.

2. Basics of Script Creation

Alright, let’s get started. A Bash script is just a text file with a bunch of commands. But for Linux to realize it’s a script and not your random diary entry, you gotta follow some rules.

Step 1: File Name and Format

Bash scripts usually have the extension .sh (but it’s not mandatory). For example:

hello_world.sh
backup_script.sh

Step 2: The Mandatory Shebang

Every Bash script starts with this line:

#!/bin/bash

This line is called the shebang, and it tells the system to use the /bin/bash interpreter to execute the script. Without it, the system will just stare at your script, sigh, and... do nothing.

Step 3: A Simple Script

Let’s create and run a script that prints "Hello, World!". I mean, why not?

  1. Create a file:

    nano hello_world.sh
    
  2. Add the following lines:

    #!/bin/bash
    echo "Hello, World!"
  3. Make the file executable:

    chmod +x hello_world.sh
    
  4. Run the script:

    ./hello_world.sh
    

Your screen will show:

Hello, World!

3. Working with Variables

Variables are storage for data in your script. They make scripts flexible and convenient.

Creating Variables

To declare a variable, use the format:

VARIABLE_NAME="value"

Example:

NAME="Linux"
echo "Welcome to $NAME!"

Output:

Welcome to Linux!

Note: You cannot put spaces between the variable name and the = sign. If you do, bash will think you're trying to write something weird and throw an error.

Built-in Variables

Bash provides some predefined variables, like:

  • $USER — the current user.
  • $HOME — the home directory.
  • $PWD — the current working directory.

Try out this script:

#!/bin/bash
echo "Hi, $USER!"
echo "Your home directory: $HOME"
echo "You're currently working here: $PWD"

4. Getting Data from the User

Sometimes a script needs to get data from the user to work. For this, the read command is used.

Example:

#!/bin/bash
echo "What's your name?"
read NAME
echo "Hi, $NAME!"

When you run the script, you’ll be able to enter your name, and the script will greet you personally.


5. Using Commands Inside a Script

Bash lets you run commands just like you'd type them in a terminal.

For example:

#!/bin/bash
echo "Current date and time:"
date

The date command will display the current date and time, for example:

Current date and time:
Mon Oct 30 12:34:56 UTC 2023

Saving Command Output to a Variable

You can save the output of a command into a variable using $(). This is super handy for processing the data later.

Example:

#!/bin/bash
CURRENT_DATE=$(date)
echo "Now: $CURRENT_DATE"

6. Comments in Scripts

Always add comments so that you can understand what you wrote a month later. Use the # symbol for comments:

#!/bin/bash
# This is a welcome script
echo "Welcome to the world of Bash!"

Comments are ignored by the interpreter and do not affect execution.


7. Example

Now let's write a script that checks if a file exists.

  1. Create a file:

    nano file_checker.sh
    
  2. Add the code:

    #!/bin/bash
    
    # Request file name
    echo "Enter file name:"
    read FILE_NAME
    
    # Check if the file exists
    if [ -f "$FILE_NAME" ]; then
        echo "File $FILE_NAME exists."
    else
        echo "File $FILE_NAME not found."
    fi
  3. Make the file executable and run it:

    chmod +x file_checker.sh
    ./file_checker.sh
    
  4. Example of script execution:

    Enter file name:
    test.txt
    File test.txt exists.
    

8. Typical Mistakes

Working with bash scripts is not only fun but can also sometimes lead to some serious head-scratching. Here's a list of common mistakes:

  1. Missing Shebang.
    Without the #!/bin/bash line, your script might try to run in a different interpreter, causing errors.

  2. Undeclared Variables.
    If you accidentally mistype a variable name, bash will treat it as empty. Enable strict checking mode with set -u at the start of your script.

  3. Spaces Around =.
    Never write like this: VARIABLE = "value". This will throw an error.

  4. Permissions Issues.
    If your script isn't executable, add execution permission using chmod +x.

Practical Assignment

  1. Write a script that:

    • Asks the user for their name.
    • Displays a welcome message.
    • Shows the current date and time.
  2. Write a script that:

    • Asks the user for a file name.
    • Creates the file if it doesn't exist or reports that the file already exists.

Now you know the basics of bash scripts! Next up, we'll learn to add conditions and loops, but that's a topic for another lecture. Onward to automating the world!

1
Task
Docker SELF, level 3, lesson 3
Locked
Welcome Script
Welcome Script
1
Task
Docker SELF, level 3, lesson 3
Locked
Working with variables and commands
Working with variables and commands
1
Task
Docker SELF, level 3, lesson 3
Locked
File Check Script
File Check Script
1
Task
Docker SELF, level 3, lesson 3
Locked
File creation script
File creation script
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION