从bash执行php脚本,将输出分配给bash变量 [英] Execute php script from bash , assign output to a bash variable

查看:101
本文介绍了从bash执行php脚本,将输出分配给bash变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,需要执行一些php脚本并取回结果,例如

I have a bash script which need to execute some php scripts and to get back the results e.g

#!/bin/bash
/usr/bin/php -f $HOME/lib/get_fifobuild.php

脚本get_fifobuild.php返回一个整数,我需要将其分配到bash变量中.如果有人帮助我,我将不胜感激.

The script get_fifobuild.php returns an integer which I need to assign into a bash variable. I ll appreciate if someone help me out.

谢谢:)

php show.php

php show.php

<?php 
  echo phpinfo();
  exit;
?>

bash脚本:

#!/bin/bash
HOME=`dirname $0`;
log(){
    NEW_LOG=$HOME/logs/cloud-`date +%d_%m_%Y`.log
    echo $1 >> $NEW_LOG
}
log "Date: `date`";
data=$(/usr/bin/php -f  $HOME/lib/show.php);
log $data;

输出:

Date: Fri Jun 15 19:16:00 PKT 2012
phpinfo()

还没有运气

推荐答案

myvariable=$(/usr/bin/php -f $HOME/lib/get_fifobuild.php)

会将您的php脚本的输出分配给一个名为"myvariable"的变量.

Will assign the output from your php script to a variable called "myvariable".

更新:

这会将命令的输出分配给变量,但是由于您仍然遇到问题,我也许可以提出一些建议:

This will assign the output of the command to the variable, but as you are still having problems I can perhaps suggest a few things:

  1. 您在其他位置有"get_builds.php"和"get_fifobuild.php".

  1. you have 'get_builds.php' and 'get_fifobuild.php' elsewhere.

检查$ HOME的设置是否正确.您最好在此处使用其他变量名称,因为通常将环境变量设置为您的主目录.但是,这不太可能成为问题,因为您正在从脚本中获取输出.

check that $HOME is being set correctly. You may be better with a different variable name here as that environment variable generally is set to your home directory. This however is unlikely to be the problem as you are getting output from the script.

您输入的文字是PHP文件的确切内容吗?如果您有报价 例如,在phpinfo()周围将导致输出只是字符串"phpinfo()".实际上,您根本不需要echo,并且可以使PHP文件的内容如下所示.

Is the text you gave the exact contents of your PHP file? If you have quotes around phpinfo() for example it will cause the output to just be the string "phpinfo()". In fact, you do not need the echo at all and could make the contents of your PHP file as follows.

get_fifobuild.php:

get_fifobuild.php:

<?php
    phpinfo();
?>

更新2:

尝试将脚本更改为:

#!/bin/bash
HOME=`dirname $0`;
log(){
    NEW_LOG=$HOME/logs/cloud-`date +%d_%m_%Y`.log
    echo "$1" >> $NEW_LOG
}
log "Date: `date`";
data=$(/usr/bin/php -f $HOME/lib/show.php);
log "$data";

基本上在'log'和'echo'行中的变量周围加上双引号.您遇到的问题是仅记录了php输出的第一行.

Basically adding double quotes around the variables in the 'log' and 'echo' lines. The problem you were having was that only the first line of your php output was being logged.

这篇关于从bash执行php脚本,将输出分配给bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆