Vivek Pandey
Vivek Pandey

Reputation: 23

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

Upvotes: 2

Views: 9834

Answers (3)

Wiimm
Wiimm

Reputation: 3568

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.

Upvotes: 5

dash-o
dash-o

Reputation: 14493

As best practice, unless the your code has full control over the any variable content, better to quote the variable. This will not prevent logical error (e.g, the extra sleep that modified the PIPESTATUS), but it will avoid accidental injection of code into the script (or unexpected syntax errors)

if [ "${PIPESTATUS[0]}" = 0 ] ; then 

Upvotes: -1

darnir
darnir

Reputation: 5190

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.

Upvotes: 7

Related Questions