【问题标题】:How can I match parameters in command line with one regular expression?如何将命令行中的参数与一个正则表达式匹配?
【发布时间】:2013-11-20 16:39:13
【问题描述】:

我有一个脚本,我想禁止命令行中的一些命令(shutdown、rm、init)。但它似乎不起作用,因为它似乎匹配一切: 我怎么能这样做?

[root@devnull hunix]# cat p.sh
#!/bin/bash

string=$1;

if [[ "$string" =~ [*shut*|*rm*|*init*] ]]
then
  echo "command not allowed!";
  exit 1;
fi
[root@devnull hunix]# ./p.sh shutdown
command not allowed!
[root@devnull hunix]# ./p.sh sh
command not allowed!
[root@devnull hunix]# ./p.sh rm
command not allowed!
[root@devnull hunix]# ./p.sh r
command not allowed!
[root@devnull hunix]#

【问题讨论】:

    标签: regex linux bash shell parameter-passing


    【解决方案1】:

    您将 shell glob 与正则表达式混为一谈。

    正确的正则表达式是:

    if [[ "$string" =~ ^(shut|rm|init) ]]; then
      echo "command not allowed!"
      exit 1
    fi
    

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      相关资源
      最近更新 更多