views:

39

answers:

3

I'm writing a shell script. A variable will have a url that will look at the the beginning few characters and

  1. make sure there is something before the //...so a http, https,rtmp,rtmps,rtmpe,etc....
  2. if nothing is in front of the // then tell user there is nothing...else if that value = whatever do whatever

How would I be able to do this?

+2  A: 
case "$URL" in
  http://*|https://*) echo "HTTP selected" ;;
  ftp://*|ftps://*) echo "FTP selected" ;;
  *) echo "Nothing selected" ;;
esac
Ignacio Vazquez-Abrams
A: 

Firstly you should should try coding this in some language such as perl or ruby that has extensive built-in regex capabilities. However if you really wish to do this in shell, then the sting operators are your friend:

url="something://and something else"

${url%%://*} will extract "something", i. e. the protocol being used.

${url##*://} will extract "and something else" i.e. everything to the right of ://

ennuikiller
${url##*://} works perfectly but the ${url%%://} just gives me the whole url not the protocol.
Keith
@Keith: There should be an asterisk after the two slashes.
Dennis Williamson
Dennis that did it. Thanks everyone...I was looking here...http://guru-host.eu/en/Web_hosting/Articles/Bash_and_Pattern_Matching_Operators to try and figure it out but didn't realize I had to do an asterisk. Thanks.
Keith
A: 

Ignacio has demonstrated how to do straight string matching, and ennuikiller has shown some of bash's pattern matching capabilities. But for what it's worth (and perhaps as surprising to others as to me), bash is indeed capable of full regexp pattern matching:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expres‐ sion and matched accordingly (as in regex(3)).

This was in the description of the [[ ]] operators for expression evaluation.

Carl Smotricz
Except that the OP said "shell" and didn't say "Bash".
Dennis Williamson