Search code examples
linuxbashshellscriptinggetopts

Checking If A Command Line Argument Exists


I have created a shell script that has 1 required argument. I want it so that the script will only run if that 1 argument is present, else it will exit.

Here's my code:

#!/bin/bash

branch=stable

# Custom options/arguments
usage() { # usage code }

while getopts ":bs:" opt; do
    case $opt in
        b)
            branch=development
            ;;
        s)
            site=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done

shift $((OPTIND-1))

if [ -z "${s}" ]; then
    echo "
        $(tput setaf 1)ERROR:
        =========================$(tput sgr0)
        $(tput setaf 6)No website name provided:
            Format: <example.com>$(tput sgr0)
    "
    exit 1;
fi

# Rest of the code to run when there are no errors - not putting here as it's irrelevant

So I would expect, that when I run sudo ./nginx-install.sh it would see there are no arguments and show the error message - which is does. But when I do sudo ./nginx-install.sh -s example.com I just get the error message again, when really I'd expect the rest of the code to run.

Can anybody point out where I am going wrong in the code? I'm new to bash scripting so been replying mainly on Google searches for help.

Thanks.


Solution

  • You assign a value to $site, not $s. Variable $s stays empty for the whole time.