Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use arguments and options in a php shell script

Tags:

shell

php

I'm trying to debug a legacy php script (😪 ) designed to be run via command line. The script is designed to take 1 optional argument, followed by N options. It was written with the intention that both of the following cases should work.

Case 1: Argument with options:

php script.php <argument> --option-a=tuesdays --option-b

Case 2: No argument with options:

php script.php --option-c

Inside the script, the argument and the options are fetched using the following:

$argument = (strpos($argv[1], '-') === 0) ? '' : $argv[1];
$options = getopt('', [
  'option-a:', 
  'option-b', 
  'option-c',
]);

Case 2 always works as expected. I receive the options and the argument is empty.

Case 1 doesn't work as expected. I received the argument, but the $options array is always empty.

I've seen the suggestion that reverses the order of the options and arguments, so I'd call it via php script --option-c <argument>. I don't want to change how it's being called, since this is a legacy script that could be used goodness-knows-where.

Is there a way I could use getopt() to fetch the options that would correct Case 1?

like image 387
Erin Avatar asked Sep 18 '25 09:09

Erin


1 Answers

I found my own answer via http://php.net/getopt. RTM.

The parsing of options will end at the first non-option found, anything that follows is discarded.

like image 77
Erin Avatar answered Sep 20 '25 01:09

Erin