by izabera · 6y ago · 0 comments
if [ exec 1>/dev/null 2>/dev/null 3>/dev/tcp/localhost/4000 ] ; then
This code runs `[ exec ]` (which tests if "exec" is a non-empty string, thus it returns true) and redirects its output and error to /dev/null, and fd 3 to /dev/tcp/whatever. If the socket opening fails, `[ exec ]` is not even executed, and the overall command returns nonzero. Completely equivalent to `: 3>/dev/tcp/localhost/4000`, which also returns nonzero if the socket can't be opened.It happens to work for the intended purpose, but not for the reasons the author intended.
In exec.sh line 1:
if [ exec 1>/dev/null 2>/dev/null 3>/dev/tcp/localhost/4000 ] ; then
^-- SC1009: The mentioned syntax error was in this if expression.
^-- SC1073: Couldn't parse this test expression. Fix to allow more checks.
^-- SC1014: Use 'if cmd; then ..' to check exit code, or 'if [[ $(cmd) == .. ]]' to check output.
^-- SC1072: Expected test to end here (don't wrap commands in []/[[]]). Fix any mentioned problems and try again.
For more information:
https://www.shellcheck.net/wiki/SC1014 -- Use 'if cmd; then ..' to check ex...
https://www.shellcheck.net/wiki/SC1072 -- Expected test to end here (don't ...
https://www.shellcheck.net/wiki/SC1073 -- Couldn't parse this test expressi... #!/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 ...