I'm trying to refactor this code:
if [ $(($1 % 4)) -eq 0 ] && [ $(($1 % 100)) -ne 0 ] || [ $(($1 % 400)) -eq 0 ] ; then
echo $T
else
echo $F
fi
into something like this:
if divisibleBy4 && notDivisibleBy100 || divisibleBy400; then
echo $T
else
echo $F
fi
note that
T="true"
F="false"
divisibleBy4 function looks like:
divisibleBy4() {
return [ $(($1 % 4)) -eq 0 ]
}
But I've tried several iterations including what I thought would definitely work.
divisibleBy4() {
if [ $(($1 % 4)) -eq 0 ]; then
return 1
else return 0
fi
}
Any idea how to properly fix the syntax so I can refactor these into functions and use them in my if statement?
When testing I'm seeing the error
syntax error: operand expected (error token is "% 4")
Another thing I tried is, but still doesn't seem to work:
INPUT=$1
divisibleBy4() {
if [ $(($INPUT % 4)) -eq 0 ]; then
return 1
else return 0
fi
}
notDivisibleBy100() {
if [ $(($INPUT % 100)) -ne 0]; then
return 1
else return 0
fi
}
divisibleBy400() {
if [ $(($INPUT % 400)) -eq 0 ]; then
return 1
else return 0
fi
}
if divisibleBy4 && notDivisibleBy100 || divisibleBy400; then
echo $T
else
echo $F
fi
or
INPUT=$1
divisibleBy4() {
return $((!($INPUT %4)))
}
notDivisibleBy100() {
return $(($INPUT %100))
}
divisibleBy400() {
return $((!($INPUT %400)))
}
(( divisibleBy4 && notDivisibleBy100 || divisibleBy400 )) && echo "true" || echo "false"
returnis not exactly like some other language'sreturns. E.g.: ``` divisibleBy4() { if [ $(($1 % 4)) -eq 0 ]; then return 5; else return 17; fi } $(divisibleBy4 4) echo $? # prints 5 $(divisibleBy4 19) echo $? # prints 17 ```$1refers to the function's arguments and not the script's. You'd have to call it asdivisibleBy4 "$1". ShellCheck autodetects this issue.INPUT=$1divisibleBy4() { if [ $(($INPUT % 4)) -eq 0 ]; then return 1 else return 0 fi } doesn't seem to work[is part of the shell's syntax, and/or that the argument toreturncan be an executable command to evaluate. Both of these are untrue.