简体   繁体   English

php/bash 脚本向命令行添加参数

[英]php/bash script adds a parameter to command line

<?php var_dump($argv); ?>

ok - run it directly - get what's expected.好的 - 直接运行它 - 得到预期的结果。

$ php /tmp/check-arg.php -s test yellow bus $ php /tmp/check-arg.php -s 测试黄色总线

array(5) {
  [0]=>
  string(18) "/tmp/check-arg.php"
  [1]=>
  string(2) "-s"
  [2]=>
  string(4) "test"
  [3]=>
  string(6) "yellow"
  [4]=>
  string(3) "bus"
}

ok - so I want to run this script as if it were a command (it's a php script that replaces an existing command), so I created this script好的 - 所以我想像运行命令一样运行这个脚本(它是一个替换现有命令的 php 脚本),所以我创建了这个脚本

$ vi /tmp/testingcommand $ vi /tmp/testing 命令

php /tmp/check-arg.php $1 $2 $3 $4 $5 $6 $7 $8 $9 $10

(edit - change the $10 to {10} is solution - or use "$@" instead of $1 $2...)

so I should be able to just所以我应该能够

$ /tmp/testingcommand -s test yellow bus $ /tmp/testingcommand -s 测试黄色总线

array(6) {
  [0]=>
  string(18) "/tmp/check-arg.php"
  [1]=>
  string(2) "-s"
  [2]=>
  string(4) "test"
  [3]=>
  string(6) "yellow"
  [4]=>
  string(3) "bus"
  [5]=>
  string(3) "-s0"
}  

OK - so where did that "-s0" come from?好的 - 那么“-s0”是从哪里来的? I've done some fiddling and it's what is in $argv[1] (-s) and a "0" (so in this case -s0)我做了一些摆弄,这就是 $argv[1] (-s) 和“0”中的内容(所以在本例中为 -s0)

Any ideas?有任何想法吗? happened on our RHEL7 as well as a Fedora 30 setup发生在我们的 RHEL7 以及 Fedora 30 设置上

since the script can be run either directly (php program.php) or via a script I can't just ignore the last index of argv[] I guess I could check argv[0] for '...php' and keep all indexs and if no...php then ignore last index因为脚本可以直接运行(php program.php)或通过脚本运行,所以我不能忽略 argv[] 的最后一个索引,我想我可以检查 argv[0] 中的“...php”并保留所有索引,如果没有...php 然后忽略最后一个索引

-s0 came from $10 . -s0来自$10 That's $1 followed by 0 .那是$1后跟0

Use ${10} to access parameter 10. You need curly braces whenever the parameter number is more than one digit.使用${10}访问参数 10。只要参数编号超过一位,就需要大括号。

Note that your code won't work properly if any of the arguments have spaces, because you're not quoting the variables.请注意,如果任何 arguments 有空格,您的代码将无法正常工作,因为您没有引用变量。 The variable value will undergo word splitting and wildcard expansion.变量值将进行分词和通配符扩展。

But if you quote all the variables, you'll get explicit '' values for the arguments that weren't supplied, which is probably not desired, either.但是,如果您引用所有变量,您将获得未提供的 arguments 的显式''值,这也可能是不希望的。

The correct way to reference all the arguments is with "$@" .引用所有 arguments 的正确方法是使用"$@"

php /tmp/check-arg.php "$@"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM