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 ...
- 01-13-2010 #1Just 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
- 01-15-2010 #2Just Joined!
- Join Date
- Oct 2008
- Posts
- 9
Code:if [[ `echo $1 | grep "\($mysubstring\)"` ]]; then .... fi
- 01-15-2010 #3
There is a simpler way to do this.
The creators of grep anticipated this need, so they made it very easy to do:
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.Code:if echo "$1" | grep -q "$mysubstring"; then .... fi
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
- 01-15-2010 #4Just 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"
- 01-15-2010 #5Just Joined!
- Join Date
- Jan 2010
- Posts
- 2
Thanks for the great explanation and example!


Reply With Quote