>_ IzzyLab

Hands-on task

This task is step 2 of the course “Your first bash script”

Move the server name into a variable

easy~6 min

The server name web-01 is written three times in the script /root/deploy.sh. Deploys now go to web-02, and later the name will change again — editing three places every time is a pain, and it's easy to miss one.

At the top of the script, right after the shebang, create a variable SERVER with the value web-02, and use it instead of the name in all three lines. The server name itself must appear in the script only once — where the variable is set.

Run the script (bash deploy.sh) and make sure all three lines now say web-02.

What you'll practise:
  • bash scripts
  • variables
  • variable expansion
  • quotes

Topic breakdown

A variable is a name that holds a value. In bash you set it like this:

GREETING="Hello"

There must be no spaces around =: bash reads GREETING = "Hello" as the command GREETING with two arguments and answers command not found.

To use the value, put $ before the name:

echo "$GREETING, world"     # Hello, world
FILE=report
echo "${FILE}_old.txt"      # report_old.txt — the braces separate the name from the text
echo "$FILE_old.txt"        # .txt — bash looks for a variable FILE_old, and there isn't one

Expansion works inside double quotes but not inside single ones: echo '$GREETING' prints $GREETING literally.

Why bother: a value that shows up in a script several times is set once at the top. When it changes, you edit one line instead of every place it's used.

Variable names are usually written in capitals — that makes them easy to tell apart from commands.

What's checked

  1. The script sets a SERVER variable
  2. The server name appears in the script once
  3. The variable is used in all three lines
  4. The script prints the new name on every line

What it looks like