Bash Scripting Basics
Variables and Arguments
Scripts become useful when they can remember values and adapt to input.
Variables
#!/bin/bash
name="Ada"
echo "Hello, $name!"
- Assign with
name="Ada"— no spaces around the= - Read the value with
$nameor${name} - Use quotes when a value contains spaces:
greeting="Hello world"
Command substitution
Capture the output of a command into a variable:
#!/bin/bash
now=$(date)
files=$(ls | wc -l)
echo "The time is $now"
echo "This directory has $files items"
Positional arguments
Scripts can accept arguments like any other command:
#!/bin/bash
echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Arg count: $#"
./args.sh hello world
# Script name: ./args.sh
# First arg: hello
# Second arg: world
# All args: hello world
# Arg count: 2
Guard against missing arguments
Before using an argument, check it exists:
if [ -z "$1" ]; then
echo "Usage: $0 <filename>"
exit 1
fi
-z tests whether the value is empty, and exit 1 reports an error.
A practical example
#!/bin/bash
dir=${1:-$HOME} # use arg 1, or default to $HOME
echo "Contents of $dir:"
ls -lah "$dir"
${1:-$HOME} means "use $1 if it is set and not empty, otherwise use $HOME".
Try it
- Write a script that greets a name passed as
$1 - Add a default name with
${1:-World} - Run it with and without an argument
Advertisement