~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Quick Bash: Check Argument Count

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

I’ve been writing more bash scripts recently and I noticed that I often check for the number of arguments before validating them in my scripts. I’ll share that small snippet here for my future self.

#!/bin/sh

set -o errexit
set -o nounset
set -o pipefail

show_usage() {
    echo "Usage: script [arg1]"
    exit 1
}

# Check argument count
if [ "$#" -ne 1 ]; then
    show_usage
fi
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :