Bash regex: grep for tilde '~' and hyphen '-' on array outline

I'm trying to create a expect_commands

bash function to check that a regex is in a file:

function expect_commands 
{
        args_array=()
        for (( i = 2; i <= $#; i++ )); do
            args_array[i]=${!i}
            if grep -Fxqe "${args_array[$i]}" "$hist_file" || grep -Fxqe "${args_array[$i]}/" "$hist_file" || grep -Fxqe "${args_array[$i]} " "$hist_file" || grep -FxqE "${args_array[$i]}" "$hist_file"
            then
                response "$1" $COUNT
            else
                tell_error "$1" $COUNT
            fi
        done
}

      

The function is called with the following arguments:

expect_commands "remove entire ~/workspace/test-website/css directory" "rm -r test-website/css" "rm -r test-website/css/" "rm -Rf ~/workspace/test-website/css" "rm -rf ~/workspace/test-website/css" "rm -R ~/workspace/test-website/css"

      

Here the argument $1

is the challenge. The $2

end-to-end arguments are each of the possible combinations that the user can enter into the terminal.

These inputs are saved to a file ~/.bash_history

and evaluated from there with grep

:

if grep -Fxqe "${args_array[$i]}" "$hist_file" || grep -Fxqe "${args_array[$i]}/" "$hist_file" || grep -Fxqe "${args_array[$i]} " "$hist_file" || grep -FxqE "${args_array[$i]}" "$hist_file"

      

The function passes with inputs such as:

rm -r test-website/css

rm -r test-website/css/

But when it comes to:

rm -Rf ~/workspace/test-website/css

rm -Rf ~/workspace/test-website/css

rm -R ~/workspace/test-website/css

grep

does not match these lines.

Some of the errors I get sometimes:

When adding the -FxqE option: grep: conflicting matchers specified

Any ideas?

+3


source to share


1 answer


Your function can be simplified: why do you need an array to store the arguments?

function expect_commands {
    local label=$1
    shift
    for arg do
        arg=$( sed "s/ ~/ $HOME/g" <<< "$arg" )    # translate ~ to $HOME
        if grep -Fxq -e "$arg" -e "$arg/" -e "$arg " "$HISTFILE"
        then
            response "$label" $COUNT
        else
            tell_error "$label" $COUNT
        fi
    done
}

      



What is it $COUNT

? Avoid global variables.

0


source







All Articles