martin
martin

Reputation: 3

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.

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.

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

Upvotes: 0

Views: 557

Answers (1)

xhienne
xhienne

Reputation: 6134

This is not due to the braces, this is due to the pipe.

When you combine commands with a pipe like command | tee, each side of the pipe is executed in a separate sub-process. 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, use pidof or pgrep instead

Upvotes: 1

Related Questions