Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIPESTATUS[0] in BASH script

I am implementing a scenario in Unix Bash scripts. I have two scripts ABC.bash and XYZ.bash. There is one condition in ABC.bash when requester does not enter Y or y scripts exit with message and do not work further. ABC.bash working fine when runs alone.Problem arises when I run it from another bash script i.e. XYZ.bash. It does not check for exit condition. Syntax of logic in XYZ.bash.

echo "Calling ABC.bash from XYZ.bash"
ABC.bash $a $b | tee -a $LOGFILE; sleep 2
if [ ${PIPESTATUS[0]} = 0 ]
then
echo "Do some work"
else
echo "Check ABC.bash input"
exit 1
fi

But when ABC.bash $a $b exit with status 2 flow still goes to IF block rather than ELSE.In log I can see message as DEBUGMODE set to 0. I need this DEBUGMODE setting as it is required but want to exit if ABC.bash exit. Ideally it should go to ELSE part as ABC.bash exit with wrong user input.

Additionally I have set up DEBUGMODE option in XYZ.bash script. Like-

if [[ -z "$1" ]]
then 
echo " ">> No input so default to 0"
DEBUGMODE=0
else
  echo "DEBUGMODE set to $1"
   DEBUGMODE=$1

fi

enter code here
like image 327
Vivek Pandey Avatar asked Dec 04 '25 04:12

Vivek Pandey


2 Answers

The problem is that PIPESTATUS is a volatile variable. That is it will be reset as soon as any other command is executed. You need to remove the call to sleep 2 if you want to inspect the PIPESTATUS.

like image 183
darnir Avatar answered Dec 06 '25 22:12

darnir


In your example, PIPESTATUS reflects the status of sleep 2. So replace

ABC.bash $a $b | tee -a $LOGFILE; sleep 2
if [ ${PIPESTATUS[0]} = 0 ]

by

ABC.bash $a $b | tee -a $LOGFILE; pstat=(${PIPESTATUS[@]}); sleep 2
if [ ${pstat[0]} = 0 ]

to save the status.

like image 42
Wiimm Avatar answered Dec 06 '25 23:12

Wiimm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!