In the bash script, I want to check if it is the first day of the month. Now I have:
if [ $DAY -eq 1 ]; then
rclone copy /tmp/$MONTH-$YEAR.tar.gz.gpg /server2/archive
fi
and I get an error:
[: -eq: unary operator expected
I tried many different syntaxes from the web, but I can't succeed. Any idea what is wrong? Ubuntu Server 18.04
Bash does not predefine
DAY
. As Jos says, the error message you're getting is the same as the message obtained when it is omitted altogether:The command
date +%d
outputs the current day of the month. If you wantDAY
to hold that value, you can use:But you can also just place the command substitution in the
[
command:date +%d
always outputs two digits, so when it is the first day of the month it outputs01
, but that is no problem. Arithmetically,01
is equal to1
, and you're rightly using-eq
, which performs numerical comparison (unlike=
, which performs textual comparison).You will notice that I have enclosed
$(date +%d)
in double quotes in the[
command. This prevents globbing and word splitting.It is a good idea always to enclose parameter expansion (
"$DAY"
), arithmetic expansion ("$((3 + 4))"
), and command substitution ("$(date +%d)"
or the less preferred form`date +%d`
) in double quotes except in the fairly uncommon case that you actually want globbing and word splitting to be performed.If you had written
"$DAY"
originally, instead of$DAY
, then you would have gotten this error from[
:That error makes much more sense.
I've also enclosed your path,
/tmp/$MONTH-$YEAR.tar.gz.gpg
, which contains the parameter expansions$MONTH
and$YEAR
, in double quotes.