In php cli mode, you can use $argc and $argv to read all parameters and numbers, such as:
ghostwu@ghostwu:~/php/php1/1$ cat go1 #!/usr/bin/php <?php echo 'Number of parameters:' . $argc . PHP_EOL; echo 'Printing parameters:' . PHP_EOL; print_r( $argv ) . PHP_EOL;
Add executable permissions to the file:
ghostwu@ghostwu:~/php/php1/1$ ls -l total 8 -rwxrwxr-x 1 ghostwu ghostwu 337 4 month 22 09:15 go -rw-rw-r-- 1 ghostwu ghostwu 126 4 month 22 09:20 go1 ghostwu@ghostwu:~/php/php1/1$ chmod a+x go1 ghostwu@ghostwu:~/php/php1/1$ ls -l total 8 -rwxrwxr-x 1 ghostwu ghostwu 337 4 month 22 09:15 go -rwxrwxr-x 1 ghostwu ghostwu 126 4 month 22 09:20 go1 ghostwu@ghostwu:~/php/php1/1$ ./go1 //Number of parameters:1 //Print parameters: Array ( [0] => ./go1 ) ghostwu@ghostwu:~/php/php1/1$ ./go1 a b c //Number of parameters:4 //Print parameters: Array ( [0] => ./go1 [1] => a [2] => b [3] => c )
If you want to execute go1 in any directory of the operating system, we need to add environment variables. I will create a directory mybin under the home directory to put the commands developed by myself
ghostwu@ghostwu:~/mybin$ tail -2 ~/.bashrc fi export PATH=~/mybin:$PATH ghostwu@ghostwu:~/mybin$ pwd /home/ghostwu/mybin ghostwu@ghostwu:~/mybin$
ghostwu@ghostwu:~/mybin$ echo $PATH /home/ghostwu/mybin:/home/ghostwu/bin:/home/ghostwu/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin ghostwu@ghostwu:~/mybin$
Print $PATH again, and it has been added. At this time, copy the developed command to ~ / mybin directory. In the future, go1 can be executed in any directory of the system
ghostwu@ghostwu:~/mybin$ cp ~/php/php1/1/go1 . ghostwu@ghostwu:~/mybin$ ls -l total 8 -rwxrwxr-x 1 ghostwu ghostwu 126 4 month 22 09:44 go1
ghostwu@ghostwu:~/mybin$ go1 Number of parameters: 1 Print parameters: Array ( [0] => /home/ghostwu/mybin/go1 ) ghostwu@ghostwu:~/mybin$ cd / ghostwu@ghostwu:/$ go1 Number of parameters: 1 Print parameters: Array ( [0] => /home/ghostwu/mybin/go1 ) ghostwu@ghostwu:/$ cd /tmp ghostwu@ghostwu:/tmp$ go1 Number of parameters: 1 Print parameters: Array ( [0] => /home/ghostwu/mybin/go1 )
Under the Linux command line, many commands, or software, have a - v parameter to display the version number. How to do this function?
$res = ''; if( $argc >= 2 ) $argv[1] == '-v' && $res = 'go version is 1.0'; echo $res . PHP_EOL;
Isn't it easy? Three lines of code will do it
ghostwu@ghostwu:~/mybin$ go -v go version is 1.0 ghostwu@ghostwu:~/mybin$ ls -l total 8 -rwxrwxr-x 1 ghostwu ghostwu 336 4 month 22 09:49 go -rwxrwxr-x 1 ghostwu ghostwu 126 4 month 22 09:44 go1 ghostwu@ghostwu:~/mybin$