[英]Why this bash script can't get the pid of the background process by $!
I have a script like that: 我有一个这样的脚本:
su lingcat -c PHPRC\=\/home\/lingcat\/etc\/php5\
PHP_FCGI_CHILDREN\=4\ \/usr\/bin\/php\-loop\.pl\ \/usr\/bin\/php5\-cgi\ \-b\
127\.0\.0\.1\:9006\ \>\>\/home\/lingcat\/logs\/php\.log\ 2\>\&1\ \<\/dev\/null\ \&\
echo\ \$\!\ \>\/var\/php\-nginx\/135488849520817\.php\.pid
This is working. 可以了 But there is too many \\
in the script, they make the code unreadable. 但是脚本中有太多\\
,它们使代码不可读。 So, I wrote a new shell script: 因此,我编写了一个新的shell脚本:
#!/bin/sh
case "$1" in
'start')
su biergaizi -c "PHPRC=/home/biergaizi/etc/php5 PHP_FCGI_CHILDREN=2
/usr/bin/php-loop.pl /usr/bin/php-cgi -b /var/run/virtualhost/php5-fpm-biergaizi.test.sock >>/home/biergaizi/logs/php.log 2>&1 </dev/null &
echo $! > /var/php-nginx/biergaizi.test.php.pid"
RETVAL=$?
;;
'stop')
su biergaizi -c "kill `cat /var/php-nginx/biergaizi.test.php.pid` ; sleep 1"
RETVAL=$?
;;
'restart')
$0 stop ; $0 start
RETVAL=$?
;;
*)
echo "Usage: $0 { start | stop }"
RETVAL=1
;;
esac
exit
But /var/php-nginx/biergaizi.test.php.pid
is empty. 但是/var/php-nginx/biergaizi.test.php.pid
为空。
What's wrong? 怎么了?
The .pid file is empty, because $!
.pid文件为空,因为$!
gets substituted by the shell executing your script, instead of the shell executing the commands you pass through su
. 被执行脚本的外壳代替,而不是执行通过su
传递命令的外壳。 And as there is no recently started background command in your script, it substitutes an empty string. 而且,由于脚本中没有最近启动的后台命令,因此它将替换为空字符串。 So, shell started by su
executes simply echo > /var/php-nginx/biergaizi.test.php.pid
. 因此,由su
启动的shell只需执行echo > /var/php-nginx/biergaizi.test.php.pid
。
To prevent that, quote your command passed to su
using single quotes, instead of double quotes. 为避免这种情况,请使用单引号而不是双引号对传递给su
的命令加引号。 It is better to do that to the "stop" command as well. 最好也对“停止”命令执行此操作。 Like this: 像这样:
su biergaizi -c 'PHPRC=/home/biergaizi/etc/php5 PHP_FCGI_CHILDREN=2
/usr/bin/php-loop.pl /usr/bin/php-cgi -b /var/run/virtualhost/php5-fpm-biergaizi.test.sock >>/home/biergaizi/logs/php.log 2>&1 </dev/null &
echo $! > /var/php-nginx/biergaizi.test.php.pid'
And this: 和这个:
su biergaizi -c 'kill `cat /var/php-nginx/biergaizi.test.php.pid` ; sleep 1'
See http://www.gnu.org/software/bash/manual/html_node/Quoting.html for details. 有关详细信息,请参见http://www.gnu.org/software/bash/manual/html_node/Quoting.html 。
try this: 尝试这个:
Escape $
from $!
逃生$
从$!
, before passing to su -c
. ,然后传递给su -c
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.