[
is a built-in command and follows the same syntax rules as other commands – arguments must be quoted and space-separated.
Specifically, the operator such as ==
is expected to be a separate argument, so you cannot omit spaces around it. If you do, it's not interpreted as an operator – the whole thing is interpreted as [ one_arg ]
, the single-argument mode, in which [
returns success when the argument is non-empty.
[ $(echo $error | grep "failed") = "failed" ]
^ ^
(Also, the operator is just =
. While bash accepts [ x == y ]
, that's non-standard.)
In addition, any string expansions like $(...)
need to be quoted – otherwise they'll be split up at spaces and can become multiple arguments (or worse):
[ "$(echo "$error" | grep failed)" = failed ]
^ ^
All that being said, you don't actually need [
here at all – the shell's if
accepts any command, so you can directly use the exit status that grep
returns:
if echo "$error" | grep -qs failed; then
echo "It failed :("
fi
Another way of doing substring checks is the case
block:
case $error in
*failed*)
echo "Fail :("
;;
*)
echo "Success!"
;;
esac
If your script is using Bash specifically (i.e. if it has #!/bin/bash
or such), you can simplify this using the [[
keyword, which does have some special syntax rules – the left-hand parameter doesn't actually need to be quoted, the equality operator is ==
, but more usefully the right-hand value can be a wildcard comparison:
if [[ $error == *failed* ]]; then
echo "Fail :("
fi
All that was about your shell scripting, but honestly? Throw out FTP entirely and replace it with, for example, SFTP (which runs via SSH, and you most likely already have it).
HOST="..."
USER="..."
# no PASS, it uses your id_rsa
DIR="/var/log/maillogs/"
LATEST="$(ls -t $DIR | head -n 2 | tail-n 1)"
FILE=$(basename $LATEST)
scp -p "$LATEST" "$USER@$HOST:/home/MailLog/" || {
echo "Fail :("
}
Even better – set up remote syslog, using e.g. syslog-ng, so that messages could be streamed live to the server.