'Bash script for loop not exiting when command is successful
I have the following script
#!/bin/bash
echo ''
maxTryTimes=10
for ((i=1; i <= maxTryTimes ; i++)); do
echo "try setup mongodb replica ${i} ..."
mongo --port 37017 setup.js > /dev/null 2>&1 && break || sleep 1
done
if (( $i <= $maxTryTimes )); then
echo 'mongodb replica setup success!'
docker exec -i stock-trading-system-stock-trading-system-db-1 sh -c 'mongoimport --port=37017 --db=stock-trading-system-db --collection=stocks --type=csv --headerline --file=//mongo-seed/MOCK_DATA.csv'
else
echo 'mongodb replica setup failed!'
fi
In the for loop, the mongo command passes first time. I know this because if i add the later mongoimport command to the end of that command then it can import the data (something which is only possible if setup.js
passes.
I got most of this script from a github repo, and im not too familiar with bash scripts, so im asking why is this for loop not exiting? From a google search it looks like it should?
This is what script.js
looks like:
/* global rs, sleep, quit */
rs.initiate()
function tryAdd (host) {
var status = rs.status()
// if exist
var isExist = status.members.find(function (member) {
return member.name === host
})
if (isExist) {
return
}
var res
// try 5 times
for (var i = 0; i < 5; i++) {
res = rs.add(host)
if (res.ok) {
return
}
sleep(500)
}
// failed
quit(1)
}
tryAdd('mongo1:27018')
tryAdd('mongo2:27019')
Solution 1:[1]
UPDATE: Not sure why this was voted down so let me explain. If you can see that the mongo command completed and what it's status was you can quickly determine if the JS is the issue or the bash code. If you see no result output then you know the code has hung up. Hence I would suggest some simple tests like this.
Example Insert code more simplistic like this:
mongo --port 37017 setup.js
result=$?
if [[ ${result} -gt 0 ]] ;then
echo "result failed [${result}]"
sleep 1
else
echo "result success [${result}]"
break
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |