在shell脚本中包含php
2013-12-08 23:43
295 查看
有时候我们可能需要在其他语言编写的Shell脚本中包含PHP编写的Shell脚本。其实非常简单,下面是一个简单的例子:
#!/bin/bash
echo This is the Bash section of the code.
/usr/local/bin/php -q << EOF
<?php
print("This is the PHP section of the code\n");
?>
EOF
其实就是调用PHP来解析下面的代码,然后输出;那么,再试试下面的代码:
#!/bin/bash
echo This is the Bash section of the code.
/usr/local/bin/php -q << EOF
<?php
$myVar = 'PHP';
print("This is the $myVar section of the code\n");
?>
EOF
可以看出两次的代码唯一的不同就是第二次使用了一个变量“$myVar”,试试运行,PHP竟然给出出错的信息:“Parse error: parse error in - on line 2”!这是因为Bash中的变量也是“$myVar”,而Bash解析器先将变量给替换掉了,要想解决这个问题,你需要在每个PHP的变量前面加上“\”转义符,那么刚才的代码修改如下:
#!/bin/bash
echo This is the Bash section of the code.
/usr/local/bin/php -q << EOF
<?php
\$myVar = 'PHP';
print("This is the \$myVar section of the code\n");
?>
EOF
#!/bin/bash
echo This is the Bash section of the code.
/usr/local/bin/php -q << EOF
<?php
print("This is the PHP section of the code\n");
?>
EOF
其实就是调用PHP来解析下面的代码,然后输出;那么,再试试下面的代码:
#!/bin/bash
echo This is the Bash section of the code.
/usr/local/bin/php -q << EOF
<?php
$myVar = 'PHP';
print("This is the $myVar section of the code\n");
?>
EOF
可以看出两次的代码唯一的不同就是第二次使用了一个变量“$myVar”,试试运行,PHP竟然给出出错的信息:“Parse error: parse error in - on line 2”!这是因为Bash中的变量也是“$myVar”,而Bash解析器先将变量给替换掉了,要想解决这个问题,你需要在每个PHP的变量前面加上“\”转义符,那么刚才的代码修改如下:
#!/bin/bash
echo This is the Bash section of the code.
/usr/local/bin/php -q << EOF
<?php
\$myVar = 'PHP';
print("This is the \$myVar section of the code\n");
?>
EOF
相关文章推荐
- shell read
- linux shell编程指南第十八章------控制流结构
- Use 'heredoc' in shell scripts
- 《生活在Linux中》之:使用Bash就是使用Emacs
- 创建一个UI输入框,以向一个重置密码的powershell脚本输入参数
- Bash's ArithmeticExpression
- Linux(四) 文件的简单压缩解压和shell应用技巧
- shell's glob
- 有用的shell工具
- 排序之希尔排序(Shell Sort)
- 使用C编译器编写shellcode
- windows下编写的shell脚本在Linux下运行,提示Syntax error
- Shell脚本学习之sed详解
- xshell设置
- Awk - 教程
- [linux Shell] Linux Shell 脚本攻略 小结
- Shell: let:not found
- Shell脚本的运行
- linux 理解shell
- Linux之编程:Linux Shell编程概述