0

I am trying to write a simple CLI script, so I have the following code saved in a file named test.php

#!/usr/bin/php -q
<?php echo "Hello world of PHP CLI!"; ?>

When I try to execute the script by running the command ./test.php I get the following output

./test.php: line 3: ?php: No such file or directory

Hello world of PHP CLI!

./test.php: line 5: syntax error near unexpected token `newline'

./test.php: line 5: `?>'

where I can see the expected output, but I also get some errors. Why am I seeing these errors and how can I fix this?

php --version output is

PHP 7.4.3 (cli) (built: Jul 5 2021 15:13:35) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

Will B.
  • 17,883
  • 4
  • 67
  • 69
  • You seem to be confused between bash scripts and PHP scripts. What you've shown is half bash and half PHP. You executed it as a bash script, and the errors are because bash doesn't quite understand all your PHP syntax properly. – ADyson Aug 05 '21 at 22:46
  • Read [the PHP manual](https://www.php.net/manual/en/features.commandline.usage.php) to understand how to use the PHP CLI correctly. – ADyson Aug 05 '21 at 22:47
  • Maybe i didn't use the terminology right, but I just followed this tutorial actually http://www.php-cli.com/php-cli-tutorial.shtml I can't understand what I might have done false – user7375077 Aug 06 '21 at 05:55
  • Also in the documentation it says the following " However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script: " – user7375077 Aug 06 '21 at 06:04
  • Ok I see. That makes a bit more sense then, thanks. I guess then maybe the path to the PHP executable is wrong? Or it doesn't like the -q? – ADyson Aug 06 '21 at 07:49
  • No, I checked the executable already. I also tried without the -q option. – user7375077 Aug 06 '21 at 09:09
  • 4
    what does `which php` and `which env` output? That would determine the [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line you put in the php file. For example I use `#!/usr/bin/env php`. Also you would need to ensure that the line-endings in the php file are in the OS's format, which is usually the cause of the error you are receiving: Unix (`"/n"` as `LF`), OSX (`"/r"` as `CR`). You can use notepad++ in Windows or [VIM](https://stackoverflow.com/q/82726/1144627) in Linux/OSX to convert the line endings. – Will B. Aug 06 '21 at 13:00

0 Answers0