Find the answer to your Linux question:
Results 1 to 5 of 5
Hello. I'm passing an argument to my shell script. In my shell script I need to verify that the argument contains a specific substring. Here's where I try to set ...
  1. #1
    Just Joined!
    Join Date
    Jan 2010
    Posts
    2

    Set Variable To SubString of Shell Script Argument

    Hello.

    I'm passing an argument to my shell script.
    In my shell script I need to verify that the argument contains a specific substring.
    Here's where I try to set a variable within the shell script:
    tmp=echo $1 | grep mysubstring
    echo $Tmp

    I'm not getting the results I need and so my question is how to set a variable within a shell script to a substring of an argument?

    Thanks,
    Rita

  2. #2
    Just Joined!
    Join Date
    Oct 2008
    Posts
    9
    Code:
    if [[ `echo $1 | grep "\($mysubstring\)"` ]]; then ....
    fi

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    There is a simpler way to do this.

    The creators of grep anticipated this need, so they made it very easy to do:
    Code:
    if echo "$1" | grep -q "$mysubstring"; then
        ....
    fi
    First of all, whenever you use variables in a Bash script, remember to quote them. This prevents spaces in the variable from confusing various programs.

    Secondly, the "-q" flag to grep stands for "quiet" and means that not only will grep not produce output, but it will also indicate the presence of the requested substring via its return value. Therefore, you do not use "if [ ... ]" (that is, don't use the square brackets), and you can use it as simply as above, with no special quotings, etc.

    Hope that helps!
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Just Joined!
    Join Date
    Oct 2008
    Posts
    9
    ouch, I must have been thinking something else when I wrote that line, I did not mean to use the square brackets at all at least I just checked the history when I played around with this yesterday

    but thanks for your explanation.

    I usually do one-liners like

    Code:
    echo "$1" | grep -q "$mysubstring" && echo "MATCH"

  5. #5
    Just Joined!
    Join Date
    Jan 2010
    Posts
    2
    Thanks for the great explanation and example!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...