Reputation: 51
I have test.sh which has multiple return condition and test1.sh just echo statement.When i run test2.sh my logic should run test.sh process the file i.e "File successfully" and call test1.sh script .It should not run the test1.sh script when other else condition was executed.i.e "File not successfully", "Input file doesn't exists in directory"
The problem i am facing is when it is executing other condition like "File not successfully", "Input file doesn't exists in directory" it is not retuning "1" as specified exit code but in turn returning 0 i.e from the OS means job was successful. So i am getting "0" from test.sh for all the different condition so test1 .sh is getting called irrespective if the file processed failed etc.Pls advice with the return code
test.sh
FILES=/export/home/input.txt
cat $FILES | nawk -F '|' '{print $1 "|" $2 "|" }' $f > output.unl
if [[ -f $FILES ]];
then if [[ $? -eq 0 ]]; then
echo "File successfully"
else
echo "File not successfully"
exit 1
fi
else
echo "Input file doesn't exists in directory" exit 1 fi
========================================================================
test1.sh
echo "Input file exists in directory"
test2.sh
echo "In test2 script"
./test.sh
echo "return code" $?
if [[ $? -eq 0 ]]; then
echo "inside"
./test1.sh
fi
Upvotes: 2
Views: 13173
Reputation: 1842
You're overwriting $?
when you use it in echo - after that, it contains the exit code of echo itself. Store it in a variable to avoid this.
echo "In test2 script"
./test.sh
testresult=$?
echo "return code" $testresult
if [[ $testresult -eq 0 ]]; then
echo "inside"
./test1.sh
fi
Edited to add: it's hard to tell what you want from test.sh as the code you pasted is incomplete and doesn't even run. It looks like you meant the cat
to be inside the if
, because otherwise it errors when the input file is missing, and your $?
test does nothing. So I rearranged it like this:
FILES=input.txt
if [[ -f $FILES ]]; then
cat $FILES | awk -F '|' '/bad/{ exit 1 }'
if [[ $? -eq 0 ]]; then
echo "File processed successfully"
else
echo "File processing failed"
exit 1
fi
else
echo "Input file doesn't exist in directory"
exit 1
fi
I've changed the awk script to demonstrate the conditions all work: now, if I put the word bad
in input.txt you'll see the "File processing failed" message, otherwise you see success; remove the file and you'll see the input file doesn't exist message.
Upvotes: 2