[英]Different results when running commands in braces within a bash script
我正在编辑一个脚本,由于脚本的长度太长,我决定将脚本的主要部分括在大括号中,并将输出转移到日志文件,而不是使用单独的日志重定向命令。 然后我注意到,检查脚本的运行副本的命令块会给出2种不同的结果,具体取决于是否将其括在括号中。
我将脚本运行为:
$ /bin/bash scriptname.bash
我的问题是为什么同一个命令块会返回2个不同的结果,以及是否有可能使命令块在花括号内工作。
下面是命令块:
#!/bin/bash
#set -x # Uncomment to debug this shell script
#
##########################################################
# DEFINE FILES AND VARIABLES HERE
##########################################################
THIS_SCRIPT=$(basename $0)
TIMESTAMP=$(date +%Y-%m-%d_%H%M%S)
LOGFILE=process_check_$TIMESTAMP.log
##########################################################
# BEGINNING OF MAIN
##########################################################
{
printf "%s\n" "Checking for currently runnning versions of this script"
MYPID=$$ # Capture this scripts PID
MYOTHERPROCESSES=$(ps -ef | \grep $THIS_SCRIPT | \grep -v $MYPID | \grep -v grep | awk '{print $2}')
if [[ "$MYOTHERPROCESSES" != "" ]]
then
printf "%s\n" "ERROR: Another version of this script is running...exiting!"
exit 2
else
printf "%s\n" "No other versions running...proceeding"
fi
printf "%s\n" "Doing some script stuff..."
exit 0
} | tee -a $LOGFILE 2>&1
# End of script
这不是由于支撑,而是由于管道。
当您将命令与类似管道的command | tee
结合使用时command | tee
command | tee
,管道的每一侧都在单独的子过程中执行。 因此,外壳程序命令在子外壳程序中执行。 这就是您检测到的子外壳。
PS:避免使用ps | grep -v grep
构造ps | grep -v grep
ps | grep -v grep
,改用pidof
或pgrep
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.