TutsFx logo

Bash Scripting Basics

Variables and Arguments

2 min read Last updated 1 hour ago

Scripts become useful when they can remember values and adapt to input.

Variables

bash
#!/bin/bash

name="Ada"
echo "Hello, $name!"
  • Assign with name="Ada"no spaces around the =
  • Read the value with $name or ${name}
  • Use quotes when a value contains spaces: greeting="Hello world"

Command substitution

Capture the output of a command into a variable:

bash
#!/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:

bash
#!/bin/bash

echo "Script name:  $0"
echo "First arg:    $1"
echo "Second arg:   $2"
echo "All args:     $@"
echo "Arg count:    $#"
bash
./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:

bash
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

bash
#!/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

  1. Write a script that greets a name passed as $1
  2. Add a default name with ${1:-World}
  3. Run it with and without an argument
Share:

We value your privacy

We use cookies to enhance your browsing experience, serve personalized ads, and analyze traffic. By clicking "Accept", you consent to our use of cookies. Read our Privacy Policy to learn more.