简体   繁体   English

如何在命令行中使用一个正则表达式匹配参数?

[英]How can I match parameters in command line with one regular expression?

I have a script, and I want to forbid some commands in command line (shutdown, rm, init). 我有一个脚本,并且我想禁止命令行中的某些命令(关闭,rm,init)。 But it seems doesn´t work because it seems to match everything: How could I do that? 但这似乎不起作用,因为它似乎可以匹配所有内容:我该怎么做?

[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]#

You're mixing up shell glob with regex. 您正在将Shell Glob与正则表达式混合在一起。

Correct regex is: 正确的正则表达式为:

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

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

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