shell to sum 2 numbers to avoid error
To avoid a error when expression is incomplete in shell
error case:
# A=# expr 1 + $A
expr: syntax error: missing argument after ‘+’
In this case 1 will be expected.
code example:
Both parameters should be checked if they are not empty.
#!/usr/bin/bash
function echo_sum() {
if [[ -z $1 ]] && [[ -z $2 ]]; then echo 0;
elif [[ -z $1 ]]; then echo `expr $2`;
elif [[ -z $2 ]]; then echo `expr $1`;
else echo `expr $1 + $2`;
fi
}
A=300
B=
C=`echo_sum $A $B`
echo "C=$C"
exit 0
elif [[ -z $1 ]]; then echo `expr $2`;
elif [[ -z $2 ]]; then echo `expr $1`;
else echo `expr $1 + $2`;
fi
}
A=300
B=
C=`echo_sum $A $B`
echo "C=$C"
exit 0
result:
# C=300
コメント
コメントを投稿