简体   繁体   English

Bash如何检查参数是否为sed模式?

[英]Bash how check if an argument is a sed patterns?

I'm working on a bash script that should receive many arguments. 我正在开发一个bash脚本,该脚本应该接收许多参数。 those arguments could be simple like: 这些参数可能很简单,例如:

Myscript [-r] [-l|-u] <dir/file names...>

or it could be just a sed patterns given instead of a simple arguments like: 或者它可能只是给定的sed模式,而不是像这样的简单参数:

Myscript  <sed pattern> <dir/file names...>

So my question is how to check if the arguments given is a sed patterns and not directory path or filename? 所以我的问题是如何检查给定的参数是否为sed模式而不是目录路径或文件名? I have done something but it doesn't work for a long path ( dir1/dir2/dir ) 我做了一些事情,但对于长路径( dir1/dir2/dir )无效

    while [[ $# > 0 ]]
    do
    key="$1"

    case $key in

        -ru|-ur)
            config_recusive
            config_upper
            shift
            ;;
        -rl|-lr)
            config_recusive
            config_lower
            shift
            ;;
        -r)
            config_recusive
            shift
            ;;
        -l)
            config_lower
            shift
            ;;
        -u)
            config_upper
            shift
            ;;
        *)
            check="^.*/.*/.*$"
            if [[ $key =~ $check ]] ; then 

                config_sed_pattern
            else
                TARGET=$key      
            fi
            shift
            ;;
    esac
done

To be more clear, here is an example of my problem when I'm trying to run the script like that: 更清楚地说,这是我尝试以这种方式运行脚本时遇到的问题的示例:

./myscript -u tmp/users/regions

its being confused taking the path ( tmp/users/regions ) as a sed patterns. 以路径( tmp/users/regions )作为sed模式感到困惑。 hope that I was clear enough. 希望我足够清楚。 waiting for your help :) thanks 等待您的帮助:)谢谢

i think you could use try run that script on something 我认为您可以使用try在某些地方运行该脚本

echo a | sed "$pattern" >/dev/null 2>/dev/null

and then check the $? 然后检查$?

if [ $? != 0 ]; then # means sed failed
#...

but maybe sed will think it will be its argument too. 但也许sed也会认为这也是它的理由。

btw, handle arguments using getopt will make things easier. 顺便说一句,使用getopt处理参数将使事情变得更容易。

i don't think the way you design argument format is good. 我认为您设计参数格式的方式不好。 maybe you think making arguments in different forms could make your program looks dynamic and awesome. 也许您认为以不同形式编写参数可能会使您的程序看起来动态而又很棒。 but now you are trying to solve a problem have nothing to do with your serious business and wasting your own time and ours. 但是现在您正试图解决问题,这与您的认真工作无关,并且浪费了自己和我们的时间。 that's not good. 这不好。 it's better to make things stupid and clear. 最好使事情变得愚蠢和清晰。

in your case, maybe you can add another argument to show it's a sed expression that follows. 在您的情况下,也许您可​​以添加另一个参数以显示它后面是一个sed表达式。

YourScript -e <sed expr> <others>

and in such a way, you will have idea about what you have done two weeks later. 这样,您就会对两周后所做的事情有所了解。

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

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