LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   simple if's in bash scripts? (https://www.linuxquestions.org/questions/programming-9/simple-ifs-in-bash-scripts-842852/)

binbash 11-07-2010 05:43 AM

simple if's in bash scripts?
 
I have been looking at: http://tldp.org/LDP/Bash-Beginners-G...ect_07_01.html

but a lot of it is to do with files and numerical comparisons

what would be the bash equivalent of:

if (http isin $2) { do something }

thanks

David the H. 11-07-2010 07:53 AM

I'm not sure what you want it to do exactly, but an if statement is really quite simple.
Code:

if <test>; then

  commands

fi

<test> can actually be any command. What if looks at is the exit code of the command used. If the exit code is 0, then the subsequent commands are executed. The most common command used here is, of course, test, which simply exits with 0 if the expression inside it evaluates as true. The [ ] brackets are actually a synonym for test.

So if you want to know whether a variable holds a certain string, then simply use a string comparison.
Code:

if [ "$var" = string ]; then
It's usually best to quote variables, which preserves whitespace and reserved characters.

However, your isin sounds more like a partial string match, which is a bit more difficult. In that case you usually need to use bash's extended [[ ]] test mechanism. This allows regex matches, among other advanced comparisons.
Code:

if [[ "$var" =~ substring ]]; then
I generally use the extended test for all my scripts, as it's more robust overall.

All of this is explained in the Bash Beginner's Guide page you're looking at. If you want more specific help, you'll have to give us more details.

binbash 11-07-2010 11:28 AM

yes "partial string match" was what I was looking for

thanks for your help - your suggestion worked


All times are GMT -5. The time now is 06:37 AM.