2

I would like to understand the function of * in the if statement as follow:

if [[ '/bin/somecommand 2>dev/null' ! = *'1'* ]];

is to examininate if the return value is return as 1, but if I leave it as

if [[ '/bin/somecommand 2>dev/null' ! = '1' ]];

it will not examinate proper value. I just try to understand what is the function of the * at the front and back of '1' does it make it a integer for comparison purpose?

I have tried the following combination

if [[ '/bin/somecommand 2>dev/null' ! = '1' ]];
if [[ '/bin/somecommand 2>dev/null' ! = 1 ]];

None of the way would return the right result other than the first one with * at the front and back of the '1'.

oguz ismail
  • 1
  • 16
  • 47
  • 69
melpen
  • 23
  • 3
  • [How do I format my code blocks?](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) – Cyrus Nov 03 '19 at 06:02
  • Are you trying to check if `somecommand` returns 1, returns any error generally, or if it *prints* 1 to stdout? – John Zwinck Nov 03 '19 at 06:04
  • I assume that instead of `'/bin/somecommand 2>dev/null'` it should correctly be `$(/bin/somecommand 2>dev/null)`. – Cyrus Nov 03 '19 at 06:05
  • Are you trying to test the *output* of `/bin/somecommand` (i.e. what it prints to standard output while it's running), or its *exit status* (a numeric code it "returns" when it exits, where normally 0 indicates that the command succeded, and something other than 0 indicates it failed)? The command you've given has several mistakes, so it's hard to tell what it's supposed to do. – Gordon Davisson Nov 03 '19 at 06:47
  • It return value of 0 or 1 to confirm if certain module is installed. – melpen Nov 03 '19 at 06:53
  • 1
    If you are worried about the `return` then just `if /bin/somecommand 2>/dev/null; then ... ` (you don't use the `[[ ... ]]` if you are checking a command return, only if checking the output [e.g. the result of the *command substitution*].) – David C. Rankin Nov 03 '19 at 06:55
  • If it's the exit status you want to test, see: [Bash conditional based on exit code of command](https://stackoverflow.com/questions/49849957/bash-conditional-based-on-exit-code-of-command) – Gordon Davisson Nov 03 '19 at 07:36

1 Answers1

1

I'm going to assume you had backticks instead of single quotes for the command, and no space in !=:

[[ `/bin/somecommand 2>dev/null` != *'1'* ]]

In a double bracket [[ .. ]] expression, the right-hand side of =/== and != is interpreted as a glob pattern, so * means "any string".

Essentially, *'1'* will match all string that contains a 1 anywhere (such as foo1bar and 3210), while '1' will only match exactly the string 1.

that other guy
  • 116,971
  • 11
  • 170
  • 194