• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

help with bash IF

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

eNightmare

Member
Joined
Feb 6, 2005
I have a problem...
I'm trying to write a bash script to compare $1

I want the first argument to be the "options" eg. script -d

so here is what i tried

if [$1 == -*]

it doesn't seem to give me the results i want. It "should" tell me whether the first character of the first positional parameter is a hyphen, but it doesn't seem to do that.

Does anyone know how to get that working right?
 
I guess I could, but its theres not much...
I'm just wondering how I can see if the first positional parameter starts with a hyphen. Its going to the else statement on every occasion with the:

if [$1 == -*]

EDIT: if you really think it will help, i'll post up the script tomorrow.
 
ideamagnate@feather:~$ f()
> {
>...if [ $1 == '-d' ]
>...then
>.....echo yup
>...else
>.....echo nope
>...fi
> }
ideamagnate@feather:~$ f -d
yup
ideamagnate@feather:~$ f -e
nope
ideamagnate@feather:~$ f 345
nope
ideamagnate@feather:~$


If you're writing anything longer than about 40-50 lines, I highly recommend The ABS Guide.
 
If you put in a wildcard in that example, I believe it would say yup for everything. In what you are doing it may work though.
 
'Fraid not. If you use an asterisk, it matches an asterisk. This is one of the areas where bash doesn't shine. If I had to do this in bash, I'd probably do something like:

ideamagnate@feather:~\ 2 $ f()
> if [ "$(echo $1 | grep -- '-.')" != "" ]; > then
>...echo yes
> else
>...echo no
> fi
ideamagnate@feather:~\ 2 $ f -quux
yes
ideamagnate@feather:~\ 2 $ f -d
yes
ideamagnate@feather:~\ 2 $ f -
no
ideamagnate@feather:~\ 2 $ f --
yes
ideamagnate@feather:~\ 2 $ f 42
no


However, it's a total hack, especially since it relies on executing a separate program to get a simple string. If I actually needed to write code that did something like that, I'd rewrite the code in something more elegant like Perl or C or 1's and 0's.

For reference, in Perl it'd be:
if ($1 ~= /-.*/){
which is much more concise and very easy to read if you're used to Perl. If you're not, it looks like something /dev/random sneezed out, but that's how Perl's supposed to be.
 
It's got its place. In the same way you wouldn't write an OS kernel in Perl or a MySQL-driven website in C, you wouldn't want to write a script of more than a couple hundred lines in bash. If you're on the CLI and need to do some operation on 500 sequentially named files, it's good to know that you can do it a with a simple bash for loop.
 
Back