In php cli mode, you can use $argc, $argv to read all parameters and their numbers, such as:
ghostwu@ghostwu:~/php/php1/1$ cat go1 #!/usr/bin/php <?php echo 'Number of arguments:' . $argc . PHP_EOL ; echo 'Print arguments:' . 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 22 09 : 15 go -rw-rw-r-- 1 ghostwu ghostwu 126 4 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 22 09 : 15 go -rwxrwxr -x 1 ghostwu ghostwu 126 4 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 we want to execute the file go1 in any directory of the operating system, we need to add environment variables. I 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, it has been added. At this time, copy the developed command to the ~/mybin directory, and then you can execute go1 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 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 very simple, 3 lines of code can be done
ghostwu@ghostwu:~/mybin$ go - v go version is 1.0 ghostwu@ghostwu:~/mybin$ ls -l total 8 -rwxrwxr -x 1 ghostwu ghostwu 336 4 22 09 : 49 go -rwxrwxr -x 1 ghostwu ghostwu 126 4 22 09 : 44 go1 ghostwu@ghostwu:~/mybin$