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.
source to share
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).
source to share