Bash test variable and program exit in same statement - bash

I am trying to test if certain variables are set and if ping exits with 0. When I do
var=1 #set for later
#"If" checks exit status correctly
if ping -c 1 an-inaccessible-thing
then
echo T
else
echo F
fi
#returns F
#"if" does not like the program in the [[ ]]
if [[ -n $var && ping -c 1 an-inaccessible-thing ]]
then
echo T
else
echo F
fi
#returns this error for obvious reasons
-bash: conditional binary operator expected
-bash: syntax error near `-c'
#if runs its test on the output of the shell, not its exit code.
if [[ -n $var && $(ping -c 1 an-inaccessible-thing) ]]
then
echo T
else
echo F
fi
#returns T, probably because it's being evaluated with -n and no the exit code
how can I test programs exit code inside the double square brackets?

Because [[ is a separate (bash builtin) program, like ping or any other program.
Do && outside of [[ ]].
[[ -n $var ]] && ping -c 1 an-inaccessible-thing

Related

Exit code as variable? $? is always zero

I noticed something strange (at least for me it's strange). I am writing a script and I need 0 or 1 as exit codes. So far so good. I have them in a simple if-else with echo $? above each condition but when I make the echo $? as a variable to call it's always showing 0 as exit code.
#!/bin/bash
exit=`echo $?`
DIRECTORY="/some/dir"
if [[ $(stat -c "%a" "$DIRECTORY") == "777" ]]
then
echo $?
#echo "The exit code is: $exit"
else
echo $?
#echo "The exit code is: $exit"
fi
#EOF
If use just "echo $?" it's all good. I receive 0 or 1. But in the commented part I always receive 0.
The $? construct contains the status code of the last command executed - exactly the last command.
The [[ is a command (bash test). Hence, you are testing the result of test.
To fix it, save the result first. For example:
result=$(stat -c "%a" "$DIRECTORY")
status=$?
... do stuff with status and result
You set the value of exit at the top of the code. This remains unchanged throughout the script. This is why you always get the same value.
Instead:
#!/bin/bash
dir='/some/dir'
if [[ "$(stat -c "%a" "$dir")" == "777" ]]; then
status=0
printf 'Permissions are 777 (status=%d)\n' "$status"
else
status=1
printf 'Permissions are not 777 (status=%d)\n' "$status"
fi
or
#!/bin/sh
dir='/some/dir'
case "$(stat -c "%a" "$dir")" in
777) echo 'Permissions are 777'; status=0 ;;
*) echo 'Permissions are not 777'; status=1 ;;
esac
Note that there is actually no need to investigate $? here. If the test succeeds, you know that it's going to be 0, otherwise non-zero.

Unexpected if statement behaviour

I was running a small bash script, but I couldn't figure out why it was entering a if block even when condition should be false.
$ cat script.sh
#!/bin/bash
if [[ "$#"="-h" || "$#"="--help" ]]
then
echo 'Show help'
exit
fi
echo 'Do stuff'
$ ./script.sh
Show help
$ bash -x script.sh
+ [[ -n =-h ]]
+ echo 'Show help'
Show help
+ exit
$ bash -x script.sh -option
+ [[ -n -option=-h ]]
+ echo 'Show help'
Show help
+ exit
So why is $# equal to -n when I didn't pass any arguments? Also even if it is, how does -n =-h evaluate to true? When I do pass an argument -option, why is it evaluated to true, too?
Whitespace is significant. Spaces between the arguments to [[ are mandatory.
if [[ "$#" = "-h" || "$#" = "--help" ]]
Also, "$#" means "all of the command-line arguments". It would be better to just check a single argument.
if [[ "$1" = "-h" || "$1" = "--help" ]]
And for what it's worth, variable expansions in [[ don't have to be quoted. It doesn't hurt, and quoting your variables actually a good habit to develop, but if you want you can remove the quotes.
if [[ $1 = -h || $1 = --help ]]
[[ string ]] return true if string is not empty, i.e. it's a shorcut for
[[ -n string ]]
In your case, the string was =-h, that's why you see
[[ -n =-h ]]
To test for string equiality, you have to use the = (or ==) operator, that must be preceded and followed by whitespace.
[[ "$#" = "-h" ]]
Note that "$#" means all the arguments:
set -- a b c
set -x
[[ "$#" == 'a b c' ]] && echo true
gives
+ [[ a b c == \a\ \b\ \c ]]
+ echo true
true
The other answers have already explained the problems with your code. This one shows that
bashisms such as [[ ... ]] are not needed,
you can gain flexibility by using a for loop to check whether at least one of the command-line argument matches -h or --help.
Script
#!/bin/sh
show_help=0
for arg in "$#"; do
shift
case "$arg" in
"--help")
show_help=1
;;
"-h")
show_help=1
;;
*)
;;
esac
done
if [ $show_help -eq 1 ]; then
printf "Show help\n"
exit
fi
Tests
After making the script (called "foo") executable, by running
chmod u+x foo
I get the following results
$ ./foo
$ ./foo -h
Show help
$ ./foo --help
Show help
$ ./foo bar
$ ./foo bar --help
Show help
$ ./foo bar --help baz -h
Show help

From bash to ksh - script throws errors but still works

I have created a simple BASH script that checks every hour for the presence of a file on a remote server. It worked error-free until I was asked to move it to a server that runs KSH.
The portion of code that errors-out is this one:
connect_string=$UID#$SERVER:$srcdir/$EVENTFILE
result=`sftp -b "$connect_string" 2>&1`
if [ echo "$result" | grep "not found" ]; then
echo "not found"
else
echo "found"
fi
These are the errors it throws:
-ksh: .[51]: [: ']' missing
grep: ]: No such file or directory
found
It still runs though and confirms that the file I am polling for is there but I need to fix this. I changed the if statement like so
if [[ echo "$result" | grep "not found" ]]; then
but it fails right away with this error
-ksh: .: syntax error: `"$result"' unexpected
What am I missing?
Your basic syntax assumptions for if are incorrect. The old [...] syntax, calls the test builtin, and [[...]] is for textual pattern matching.
As #shelter's comment, the correct syntax is:
connect_string="$UID#$SERVER:$srcdir/$EVENTFILE"
result=`sftp -b "$connect_string" 2>&1`
if echo "$result" | grep "not found" ; then
echo "not found"
else
echo "found"
fi
But this is an unnecessary use of the external grep program, you can use shell text comparison:
if [[ $result == *not\ found* ]] ; then
echo "not found"
else
echo "found"
fi
(tested with bash and ksh)
Your solution:
EXIT=`echo $?`
if [ $EXIT != 0 ]
then
...
fi
Can be improved. First, if you are going to do an arithmetic comparison, then use ((...)), not test, and I can't figure out why you have the EXIT variable:
if (( $? != 0 ))
then
...
fi
But to go full circle, you actually only need:
if sftp -b "$connect_string" 2>&1
then
...
fi
echo "$result" | grep "not found"
#capture exit status code from previous command ie grep.
if [[ $? == 0 ]]
than
echo "not found"
else
echo "found"
fi
It appears you're struggling with a basic tenet of bash/ksh control structures.
Between the if and the then keywords, the shell expects one or more commands, with
the last command in the series deciding how the if statement is processed.
The square brackets are only needed if you actually need to perform a comparison. Internally they are equivalent to the test command - if the comparison succeeds, it
results in an exit status of 0.
Example:
$ [ a == a ]
$ echo $?
0
$ [ a == b ]
$ echo $?
1
Which is equivalent to:
$ test a == a
$ echo $?
0
$ test a == b
$ echo $?
1
I changed my approach to this.
connect_string=$UID#$SERVER:$srcdir/$EVENTFILE
result=`sftp "$connect_string" 2>&1`
EXIT=`echo $?`
if [ $EXIT != 0 ]
then
echo "file not found"
exit 1
else
echo "file found"
exit 0
fi
It takes care of my problem. Thanks to all.

What causes the exit status to change for the same command even when the output is identical?

In the below code, I am trying to check if the command within the if condition completed successfully and that the data was pushed into the target file temp.txt.
Consider:
#!/usr/bin/ksh
A=4
B=1
$(tail -n $(( $A - $B )) sample.txt > temp.txt)
echo "1. Exit status:"$?
if [[ $( tail -n $(( $A - $B )) sample.txt > temp.txt ) ]]; then
echo "2. Exit status:"$?
echo "Command completed successfully"
else
echo "3. Exit status:"$?
echo "Command was unsuccessfully"
fi
Output:
$ sh sample.sh
1. Exit status:0
3. Exit status:1
Now I can't get why the exit status changes above.. when the output of both the instances of the tail commands are identical. Where am I going wrong here..?
In the first case, you're getting the exit status of a call to the tail command (the subshell you spawned with $() preserves the last exit status)
In the second case, you're getting the exit status of a call to the [[ ]] Bash built-in. But this is actually testing the output of your tail command, which is a completely different operation. And since that output is empty, the test fails.
Consider :
$ [[ "" ]] # Testing an empty string
$ echo $? # exit status 1, because empty strings are considered equivalent to FALSE
1
$ echo # Empty output
$ echo $? # exit status 0, the echo command executed without errors
0
$ [[ $(echo) ]] # Testing the output of the echo command
$ echo $? # exit status 1, just like the first example.
1
$ echo foo
foo
$ echo $? # No errors here either
0
$ [[ $(echo foo) ]]
$ echo $? # Exit status 0, but this is **NOT** the exit status of the echo command.
0

bash - Possible to 'override' the test ([[)-builtin?

Is it possible to override Bash's test builtin? So that
[[ $1 = 'a' ]]
not just does the test but also outputs which result was expected when it fails? Something like
echo "Expected $1 to be a.'
EDIT
I know this is bad :-).
The test expression compound command does real short-circuiting that affects all expansions.
$ set -x
$ [[ 0 -gt x=1+1 || ++x -eq $(tee /dev/fd/3 <<<$x) && $(echo 'nope' >&3) ]] 3>&1
+ [[ 0 -gt x=1+1 ]]
++ tee /dev/fd/2
2
+ [[ ++x -eq 2 ]]
So yes you could do anything in a single test expression. In reality it's quite rare to have a test produce a side-effect, and almost never used to produce output.
Also yes, reserved words can be overridden. Bash is more lenient with ksh-style function definitions than POSIX style (which still allows some invalid names).
function [[ { [ "${#:1:${##}-1}" ]; }; \[[ -a -o -a -o -a ]] || echo lulz
Yet another forky bomb.
if function function if function if if \function & then \if & fi && \if & then \function & fi && then \function fi
Something like this?
if [[ $1 == 'a' ]]; then
echo "all right";
else
echo 'Expected $1 to be "a"'
fi
Anyway, what's the point of the test if you only expect one answer? Or do you mean that for debugging purposes?
[[ 'a' = 'a' ]] || echo "failed"
[[ 'b' = 'a' ]] || echo "failed"
failed

Resources