#!/bin/bash
#-----------#
# Functions #
#-----------#
function RT
{
declare __line;
for __line in "${@:2}";
do
if ! [[ "$__line" =~ $1 ]];
then
return 1;
fi
done
return 0;
}
#-----------#
# Main #
#-----------#
regex_v='^[0-9]*$';
value_1_v='12345';
value_2_v='67890';
if RT "$regex_v" "$value_1_v" "$value_2_v";
then
printf 'Valid';
else
printf 'Invalid';
fi
描述
函数RT或Regex Test
# Declare a local variable for a loop.
declare __line;
# Loop for every argument's value except the first - regex rule
for __line in "${@:2}";
# Test the value and return a **non-zero** return code if failed.
# Alternative: if [[ ! "$__line" =~ $1 ]];
if ! [[ "$__line" =~ $1 ]];
# Return a **zero** return code - success.
return 0;
主要代码
# Define arguments for the function to test
regex_v='^[0-9]*$'; # Regex rule
value_1_v='12345'; # First value
value_2_v='67890'; # Second value
# A statement which runs the function with specified arguments
# and executes `printf 'Valid';` if succeeded, else - `printf 'Invalid';`
if RT "$regex_v" "$value_v";