Shell: Checking if argument exists and matches expression Shell: Checking if argument exists and matches expression bash bash

Shell: Checking if argument exists and matches expression


if [[ -n "$1" ]] && [[ "${1#*.}" == "tar.gz" ]]; then

-eq: (equal) for arithmetic tests

==: to compare strings

See: help test


You can also use:

case "$1" in        *.tar.gz) ;; #passed        *) echo "wrong/missing argument $1"; exit 1;;esacecho "ok arg: $1"


As long as the file is in the correct YYYY-MM.tar.gz format, it obviously is non-empty and ends in .tar.gz as well. Check with a regular expression:

if ! [[ $1 =~ [0-9]{4}-[0-9]{1,2}.tar.gz ]]; then    echo "Argument 1 not in correct YYYY-MM.tar.gz format"    exit 1fi

Obviously, the regular expression above is too general, allowing names like 0193-67.tar.gz. You can adjust it to be as specific as you need it to be for your application, though. I might recommend

[1-9][0-9]{3}-([1-9]|10|11|12).tar.gz

to allow only 4-digit years starting with 1000 (support for the first millennium ACE seems unnecessary) and only months 1-12 (no leading zero).