Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell: Checking if argument exists and matches expression

Tags:

regex

bash

shell

I'm new to shell scripting and 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 this command:

# script.sh YYYY-MM.tar.gz

I believe what I have is

  1. if the YYYY-MM.tar.gz is not after script.sh it will echo "Missing valid argument" and
  2. if the file does not end in .tar.gz it echo's the same error.

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

like image 969
Mark Avatar asked Feb 11 '23 22:02

Mark


2 Answers

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

-eq: (equal) for arithmetic tests

==: to compare strings

See: help test

like image 162
Cyrus Avatar answered Feb 15 '23 10:02

Cyrus


You can also use:

case "$1" in
        *.tar.gz) ;; #passed
        *) echo "wrong/missing argument $1"; exit 1;;
esac
echo "ok arg: $1"
like image 32
jm666 Avatar answered Feb 15 '23 11:02

jm666