Shell: check if an argument exists and match an expression

I am new to shell scripting and am trying to write the ability to check if an argument exists and if it matches an expression. I'm not sure how to write expressions, so this is what I have so far:

#!/bin/bash

if [[ -n "$1"] && [${1#*.} -eq "tar.gz"]]; then
  echo "Passed";
else 
  echo "Missing valid argument"
fi

      

To run the script, I would type the following command:

# script.sh YYYY-MM.tar.gz

      

I believe that I have

  • if YYYY-MM.tar.gz is not after script.sh it will echo "Missing a valid argument" and
  • If the file doesn't end in .tar.gz, it repeats the same error.

However, I want to also check if the full filename is in YYYY-MM.tar.gz format.

+3


source to share


3 answers


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

      

-eq

: (equal) for arithmetic tests



==

: compare strings

See: help test

+4


source


You can also use:



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

      

+2


source


As long as the file is in the correct format YYYY-MM.tar.gz

, it is clearly not empty and ends with .tar.gz

. Check your regex:

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

      

Obviously, the regex above is too general to use names like 0193-67.tar.gz. However, you can customize it however you like for your application. I would recommend

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

      

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

0


source







All Articles