简体   繁体   English

Bash正则表达式:Grep表示阵列循环中的'〜'和连字符' - '

[英]Bash regex: Grep for tilde '~' and hyphen '-' on array loop

I'm trying to create an expect_commands bash function to check for a regex to be on a file: 我正在尝试创建一个expect_commands bash函数来检查正则表达式是否在文件上:

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"

Where argument $1 is the task. 其中参数$1是任务。 Arguments from $2 to the end are each of the possible combinations that the user may input to the terminal. $2到结尾的参数是用户可以输入到终端的每种可能的组合。

These inputs are saved into the ~/.bash_history file and evaluated from there with grep : 这些输入保存在~/.bash_history文件中,并使用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 like: 该函数通过以下输入传递:

rm -r test-website/css rm -r test-website/css/ 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 rm -Rf ~/workspace/test-website/css rm -rf ~/workspace/test-website/css rm -R ~/workspace/test-website/css

grep fails to match those lines. grep无法匹配这些行。

Some of the errors I get sometimes are: 我有时会遇到的一些错误是:

When adding the -FxqE option: grep: conflicting matchers specified 添加-FxqE选项时: grep: conflicting matchers specified Conflicting matchers

Any ideas? 有任何想法吗?

Your function can be simplified: why do you need an array to hold 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 $COUNT ? 什么是$COUNT Avoid global variables. 避免全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM