user8115103
user8115103

Reputation:

Bash Regex Accepts [Number], but i want only Number accepted

I have some Problems and i dont know what causes them. In my Script (bash) i want to ask with "if" if my $1 is a number. Only 0-9 Digits and optinal "-". When i make

`if [[ "$1" -eq "$1" ]]` 

or

 if `([[ $1 =~ ^-?[0-9]+$ ]]`

Both times i can make

`./myscript [number]`

or

./myscript number*

and the number got accepted. But of course i dont want [number] to be a number as parameter. Only Numbers without any other symbols, brackets or other stuff

Can Someone tell me where is my Problem? I only want to understand why the bash acts like this. I dont want some complete code snipped that solve my Problems. Only some ideas was causes the Problem Greetings

Upvotes: 1

Views: 469

Answers (1)

ArturFH
ArturFH

Reputation: 1787

I guess in current directory you have a file named number. Please see log below:

[arturcz@home xxx]$ ls -la
total 4
drwxr-xr-x  2 arturcz arturcz  60 Jun  5 16:27 .
drwxrwxrwt 16 root    root     580 Jun  5 16:27 ..
-rwxr-xr-x  1 arturcz arturcz  88 Jun  5 16:24 number.sh
[arturcz@home xxx]$ cat number.sh
#!/bin/bash
if [[ $1 =~ ^-?[0-9]+$ ]]; then
    echo Number
else
    echo Not number
fi
[arturcz@home xxx]$ ./number.sh 1
Number
[arturcz@home xxx]$ ./number.sh [1]
Not number
[arturcz@home xxx]$ ./number.sh 1*
Not number
[arturcz@home xxx]$ touch 1
[arturcz@home xxx]$ ./number.sh [1]
Number
[arturcz@home xxx]$ ./number.sh 1*
Number
[arturcz@home xxx]$

If you want to avoid parameter to be interpreted and expanded by bash, put in in single or double quotation marks:

[arturcz@home xxx]$ ./number.sh '1*'
Not number
[arturcz@home xxx]$ ./number.sh '[1]'
Not number

Upvotes: 4

Related Questions