Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add shebang #! with php script on linux?

Tags:

linux

php

shebang

I'm having a little issue with adding shebang #! with my php script on RedHat linux. I have a small piece of test code with shebang added (I've tried different variations as well), but I get the following error message everytime I try to run the script.

Error msg:

-bash: script.php: command not found 

Test script:

#!/bin/env php     <?php echo "test"; ?> 

Shebang #! variations:

#!/usr/bin/php #!/usr/bin/env php 
like image 325
user2799603 Avatar asked Feb 12 '14 15:02

user2799603


People also ask

How do you make a shebang?

Starting a Script With #! It is called a shebang or a "bang" line. It is nothing but the absolute path to the Bash interpreter. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash.

How do you use shebang?

The #! shebang is used to tell the kernel which interpreter should be used to run the commands present in the file. When we run a file starting with #! , the kernel opens the file and takes the contents written right after the #! until the end of the line.

Where do I put my shebang line?

The shebang character sequence is always used in the first line of any file. The statement that mentions the program's path is made by using the shebang character first and then the path of the interpreter program.

What is shebang command?

In computing, a shebang is the character sequence consisting of the characters number sign and exclamation mark ( #!) at the beginning of a script. It is also called sharp-exclamation, sha-bang, hashbang, pound-bang, or hash-pling.


2 Answers

It should (for most systems) be #!/usr/bin/env php, but your error isn't related to that.

-bash: script.php: command not found 

It says that script.php is not found.

If the problem was the shebang line then the error would say something like:

bash: script.php: /usr/env: bad interpreter: No such file or directory 

Presumably, you are typing script.php and the file is not in a directory on your $PATH or is not executable.

  1. Make it executable: chmod +x script.php.
  2. Type the path to it instead of just the filename, if it is in the current directory then: ./script.php.

Instead of 2, you can move/copy/symlink the file to somewhere listed in $PATH or modify the $PATH to include the directory containing the script.

like image 126
Quentin Avatar answered Sep 23 '22 12:09

Quentin


If you script is not located in your /usr/local/bin and is executable, you have to prefix calling your script with php like this:

php myscrip.php 

For shebangs, here is what I use:

Like this:

#!/usr/bin/php 

or this:

#!/usr/bin/env php 
like image 27
Banago Avatar answered Sep 22 '22 12:09

Banago