Variables & Input
Variables allow you to store and reuse data throughout your script. Unlike many languages, shell variables are loosely typed.
1. Defining Variables
- Assignment:
VARIABLE_NAME="value"(Note: No spaces around=). - Access: Use
$before the name (e.g.,$VARIABLE_NAME).
#!/bin/bash
NAME="DevOps Engineer"
echo "Hello, $NAME!"2. Command Substitution
Command substitution allows the output of a command to be replaced as a string.
- Syntax:
$(command)or`command`.
#!/bin/bash
CURRENT_DATE=$(date)
USER_COUNT=$(who | wc -l)
echo "The current date is: $CURRENT_DATE"
echo "There are $USER_COUNT users logged in."3. Positional Parameters
When you run a script like ./myscript.py arg1 arg2, these arguments are available as special variables.
| Variable | Meaning |
|---|---|
$0 | The name of the script itself. |
$1, $2... | The 1st, 2nd argument passed. |
$# | The number of arguments passed. |
$@ | All arguments passed as a list. |
4. Getting User Input: read
You can make your scripts interactive using the read command.
#!/bin/bash
echo "What is your server environment? (prod/stage)"
read ENV
echo "Deploying to $ENV environment..."[!IMPORTANT] Quoting Variables Always wrap your variables in double quotes (e.g.,
"$NAME") when using them. This prevents errors if the variable contains spaces or special characters.