supertren
supertren

Reputation: 65

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). 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]#

Upvotes: 1

Views: 111

Answers (1)

anubhava
anubhava

Reputation: 784958

You're mixing up shell glob with regex.

Correct regex is:

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

Upvotes: 5

Related Questions