I have this function in bash, where an if-statement won't be run until the end of the scope, but only runs the first command after the if-statement, and then continues with the first-next command after the end of the scope. I can't seem to figure out why this happens, or why it is even possible in the first place.
The code in question:
function log() {
if [[ "x$disablelog" != "xtrue" && "x$logfile" != "x" ]]; then
if [[ ! -w "$logfile" ]]; then
touch "$logfile" &>/dev/null
if [[ "$?" != "0" ]]; then
debugout "Cannot write log file $logfile, disabling log."
disablelog="true"
echo "This, and the lines above/below are never executed. However, debugout is."
return 1
fi
fi
echo "[$(date +%s)] $@" >> "$logfile"
fi
}
I have encountered this problem a few times in the past and have never been able to find any information about it, I'd like to find out what I'm doing wrong now once and for all.
Update: Adding debugout as per request:
function debugout() {
if [[ "x$debug" != "xtrue" ]]; then
return
fi
if [[ "x$color" == "xtrue" ]]; then
echo -e "\e[1;36mDEBUG:\e[0m $@"
else
echo -e "DEBUG: $@"
fi
log "DEBUG: $@"
}
The same thing happens when I just use normal echo, or any other command though. (Edit: apparently not...)
debugout
might be required here, I suspect that's what causing the issue. – cmh Jun 7 at 12:53"x$foo" != "x$bar"
trick inbash
;[[ $disablelog != true ]]
is sufficient. – chepner Jun 7 at 12:57set -xv
to see the actual values of the variables. – choroba Jun 7 at 13:05