[英]Different results when running commands in braces within a bash script
I was editing a script and as the script was getting a bit long I decided to enclose the main part of the script in braces and divert the output to a log file instead of having individual log redirects for commands. 我正在编辑一个脚本,由于脚本的长度太长,我决定将脚本的主要部分括在大括号中,并将输出转移到日志文件,而不是使用单独的日志重定向命令。 Then I noticed that a command block that checks for a running copy of the script gives 2 different results depending if it is enclosed in braces.
然后我注意到,检查脚本的运行副本的命令块会给出2种不同的结果,具体取决于是否将其括在括号中。
I run the script as: 我将脚本运行为:
$ /bin/bash scriptname.bash
My question is why the same command block returns 2 different results and if it is possible to have the command block work inside the braces. 我的问题是为什么同一个命令块会返回2个不同的结果,以及是否有可能使命令块在花括号内工作。
Below is the command block: 下面是命令块:
#!/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
This is not due to the braces, this is due to the pipe. 这不是由于支撑,而是由于管道。
When you combine commands with a pipe like command | tee
当您将命令与类似管道的
command | tee
结合使用时command | tee
command | tee
, each side of the pipe is executed in a separate sub-process. command | tee
,管道的每一侧都在单独的子过程中执行。 Shell commands are therefore executed in a sub-shell. 因此,外壳程序命令在子外壳程序中执行。 That's this sub-shell that you detect.
这就是您检测到的子外壳。
PS: avoid constructs like ps | grep -v grep
PS:避免使用
ps | grep -v grep
构造ps | grep -v grep
ps | grep -v grep
, use pidof
or pgrep
instead ps | grep -v grep
,改用pidof
或pgrep
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.