Shell脚本变量无法捕获进程计数问题求助
解决Shell脚本中无法捕获进程计数到变量的问题
嘿,我发现你的问题所在了!让我一步步给你解释:
核心问题分析
你的代码里这一行写法有两个关键问题:
count_build_status=`ps -ef | grep BDD_PreCheck.sh | grep -c FT_BGmgmt` | tee -a ${logFile}
- 子shell变量作用域问题:当你把赋值语句和
tee用管道连接时,shell会在子shell中执行赋值操作。这意味着变量count_build_status只在子shell中有效,回到父shell后变量就变成空的了。 - 进程匹配不准确:单独执行
ps -ef | grep BDD_PreCheck.sh时,会把当前执行的grep进程也匹配进去,可能导致计数结果不符合预期(比如明明没有目标进程却返回1)。
解决方案
这里给你两种可行的修改方式:
方案1:把tee整合到命令替换中
将tee放到命令替换(推荐用$()替代反引号,可读性更好)内部,这样命令的输出会同时被捕获到变量,并且写入日志文件。同时加上grep -v grep排除自身进程:
#!/bin/ksh ## Checking whether or not the Previous Build is Completed count_build_status=$(ps -ef | grep BDD_PreCheck.sh | grep -v grep | grep -c FT_BGmgmt | tee -a "${logFile}") echo "The Value of Count Build Status is $count_build_status" if [[ "${count_build_status}" != "0" ]] then echo "INFO - The previous build has not ended yet. Please Wait for some time or contact the Administrator" | tee -a "${logFile}" exit 1; fi exit 0;
方案2:先赋值再写入日志
如果不想把tee放在命令替换里,可以先把进程计数赋值给变量,再单独将变量内容写入日志,这样能彻底避免子shell的作用域问题:
#!/bin/ksh ## Checking whether or not the Previous Build is Completed count_build_status=$(ps -ef | grep BDD_PreCheck.sh | grep -v grep | grep -c FT_BGmgmt) # 先把变量值写入日志 echo "${count_build_status}" | tee -a "${logFile}" echo "The Value of Count Build Status is $count_build_status" if [[ "${count_build_status}" != "0" ]] then echo "INFO - The previous build has not ended yet. Please Wait for some time or contact the Administrator" | tee -a "${logFile}" exit 1; fi exit 0;
额外提示
- 引用变量时加上双引号(比如
"${logFile}"),避免当变量包含空格或特殊字符时出现意外错误。 $()比反引号的兼容性更好,也支持嵌套写法,推荐日常使用。
内容的提问来源于stack exchange,提问作者Rohit Verma
相关产品推荐
相关产品推荐

