【问题标题】:How to grep a exact word from a variable contains sentence如何从包含句子的变量中获取确切的单词
【发布时间】:2014-02-22 19:15:24
【问题描述】:

我已尽我所能得到结果,但我做不到。我请求你以正确的方式指导我。

Bellow 是我的 bash 脚本,它实际上是一个 init.d 脚本。

#!/bin/bash

LOG_LEVEL="info debug_rpc warn test critical debug_sql error debug debug_rpc_answer notset"
CHECK_LOG_LEVEL=$2

logcheck() {
if [ ! -z $CHECK_LOG_LEVEL ]; then
    if [ "$(grep -o "$LOG_LEVEL")" == "$CHECK_LOG_LEVEL" ]; then
       echo "Starting the daemon with log_level"
    else
        echo "Check if the log-level argument name is correct!"
    exit 1
    fi
else
    echo "Starting the daemon"
fi
}

case "${1}" in
        start)
                logcheck
                ;;
        esac

exit 0

我希望 grep 匹配确切的单词。因为 debug_rpc、debug_rpc_answer、debug_sql

如果您的用户通过运行以下脚本而出现拼写错误: sudo /etc/init.d/myscript.sh start debug_rp

需要显示 {echo "Check if the log-level argument name is correct!"}

我正在尝试将存储在变量 $CHECK_LOG_LEVE 中的确切用户参数与内容 $LOG_LEVEL 匹配

对此的任何指导或解决方法..

谢谢。

【问题讨论】:

    标签: bash grep


    【解决方案1】:
    LOG_LEVEL="info debug_rpc warn test critical debug_sql error debug debug_rpc_answer notset"
    CHECK_LOG_LEVEL=$2
    
    # spaces below are very deliberate
    if [[ " $LOG_LEVEL " != *" $CHECK_LOG_LEVEL "* ]]; then
        echo "invalid log level" >&2
        exit 1
    fi
    

    “debug_rp”不会通过该检查,但如果有人确定提供无效输入,“info debug_rpc”会通过


    为了精确匹配,使用数组:

    LOG_LEVEL=( info debug_rpc warn test critical debug_sql error debug debug_rpc_answer notset )
    CHECK_LOG_LEVEL=$2
    
    found=false
    for lvl in "${LOG_LEVEL[@]}"; do
        if [[ $CHECK_LOG_LEVEL == $lvl ]]; then
            found=true
            break
        fi
    done
    if ! $found; then
        echo "invalid log level" >&2
        exit 1
    fi
    

    【讨论】:

    • 是的,你是对的.. info debug_rpc get pass.. 所有我都试图让参数与空格之间的单词相匹配....不过我很感谢你的回复。但如果有任何解决方法.. 它会很棒。
    • Glenn.. 在我的测试中,您的第二个代码仍然给出 found=true。如果我们以 ./test.sh start info debug_rpc .. 的形式执行脚本,则数组具有第一个单词 (info)。这是因为“debug_rpc”被作为第三个参数。我必须在脚本中提供以检查用户是否提供了任何第三个参数。如果是这样..然后退出脚本错误。不管怎么说,还是要谢谢你。我很欣赏你的想法。我指的是这个.. :-) codeandfury.blogspot.in/2006/12/…
    【解决方案2】:

    你可以使用这个grep -qw(匹配词):

    if grep -qw "$CHECK_LOG_LEVEL" <<< "$LOG_LEVEL"; then
        echo "valid log-level argument"
    else
        echo "Check if the log-level argument name is correct!"
    fi
    

    之后您可以使用$?查看退货状态

    【讨论】:

    • 建议直接条件 (if grep -qw ...) 可能比使用 $? 更好。
    • 是的,当然可以(而且应该)直接在if条件下使用。
    • 我打算建议if [ ! -z "echo $LOG_LEVEL | grep -w $CHECK_LOG_LEVEL" ]; then... 但这有点整洁,所以+1
    • 以任何方式显示回显“检查日志级别参数名称是否正确!”只有一次。它现在正在显示每张支票。不过我很喜欢答案。
    • 如果它不在循环中,它应该只显示一次,并确保你在这个错误之后exit 1
    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 2013-04-08
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多