[英]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.