Page 1 of 1

CLI Options Parser

Posted: Fri Aug 17, 2007 4:54 am
by Ollie Saunders
I'm trying to write a high quality command line argument parser that adheres to GNU guidelines which are inspired by POSIX guidelines. But I've discovered a fundamental problem in doing this.

When executing PHP from the command line I've been using the $argv variable to get access to the arguments. Unfortunately this doesn't give you access to the actual command executed but instead something already parsed, in part, by the shell or PHP (I don't know which). Whatever it is you end up with some kind of bastardized implementation that does things incorrectly:

Code: Select all

$ echo '#!/usr/bin/php
> <?php
> print_r($argv);' > test.php
$ chmod +x test.php
$ ./test.php -
Array
(
    [0] => ./test.php
    [1] => -
)
$ ./test.php \-
Array
(
    [0] => ./test.php
    [1] => -
)
$ # no discernible difference despite the escape
$ foo='monkey love'
$ ./test.php $foo
Array
(
    [0] => ./test.php
    [1] => monkey
    [2] => love
)
# "monkey love" should be combined in element 1
I'm sure there are more problems too. How do C programs do it? Is there are realistic solution? Perhaps this is a good enough reason to use a completely non-standard syntax. At least it would be safe and predictable.

Posted: Fri Aug 17, 2007 5:10 am
by Ollie Saunders
Sorry I'm wrong on that second one. monkey and love coming up as separate args is the correct behaviour. Ugghh bash is a pile of poop, it really is.

Posted: Fri Aug 17, 2007 5:16 am
by Chris Corbyn
BASH still supports this though:

Code: Select all

$ foo='monkey love'
$ ./test.php "$foo"

Posted: Fri Aug 17, 2007 5:20 am
by Ollie Saunders
Yeah I realised that. It just find the behaviour of bash overall very counter-intuitive, by default it does really bizarre things and you have to go out of your way to make behave normally.