5 ms·
I'm not sure if the code example changed on the linked page after your comment, but I see this code: #!/bin/bash if exec 3>/dev/tcp/localhost/4000 ; then
by gricardo99 6y ago
I'm not sure if the code example changed on the linked page after your comment, but I see this code:
#!/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?
- gricardo99 6y agoSure enough, I tested this, and the server up/down is reversed from what it should be: > 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
- dllthomas 6y agoIn the quoted code, "server up" is for a zero result - `if` is reversed from what you think it is: > if true; then echo yup; fi yup > true > echo $? 0
- gricardo99 6y agoindeed you are right. Thanks for the reply. I'm too accustomed to seeing code like: 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 ...
- fl0wenol 6y agoYou really really should use if COMMAND logic, in the event that all you care about is zero or non-zero result. I find it easier to follow for shell control flow. It also works for shell functions.
- dllthomas 6y agoFrom one perspective, if [ $? -eq 0 ]; then ... is actually an instance of if COMMAND; then ... because [ is itself a command.
- gricardo99 6y agoyep, I think that's the key point I need to drill into my head. The unix/linux idiom where 0 is true/success and non-zero is a failure can be counter-intuitive when combined with "if" (at least for me, hence my mistake reading the code). In most/other computing contexts "if 0" is never taken. I think this might explain why I've seen a lot more bash code that is explicitly written in the form more familiar to "if" usage in other languages (pseudo-code): "if res == 0". But "if COMMAND" is taking care of the interpretation of the return code, so doing the explicit compare is redundant.
- who23 6y agoHey I'm the author. Bash treats 0 exit codes as a success, so the "server up" echo runs if the connection is made.