by gricardo99 · 6y ago · 0 comments
#!/bin/bash
if exec 3>/dev/tcp/localhost/4000 ; then
echo "server up!"
else
echo "server down."
fi
Which also confused me for similar reasons to your comment. I'm not familiar with exec, but generally non-zero return means a fail, and zero means success. So why is the "server up" for non-zero result? > exec 3>/dev/tcp/localhost/4000
bash: connect: Connection refused
bash: /dev/tcp/localhost/4000: Connection refused
> echo $?
1
But if a localhost port is listening (in another terminal window: > nc -l localhost 4000): > exec 3>/dev/tcp/localhost/4000
> echo $?
0 > if true; then echo yup; fi
yup
> true
> echo $?
0 if [ $? -eq 0 ]; then echo "pass";else echo "fail";fi
But without the expression '[ ... ]' shell/bash does indeed treat zero return code (success) as boolean true.
For whatever reason I have not seen much (if any) bash code that simply uses: if COMMAND; then ...It also works for shell functions.
if [ $? -eq 0 ]; then ...
is actually an instance of if COMMAND; then ...
because [ is itself a command.