CLI Options Parser

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

CLI Options Parser

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

BASH still supports this though:

Code: Select all

$ foo='monkey love'
$ ./test.php "$foo"
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
Post Reply