How to apply multiple validations to an argument in bash script? - bash

I have a bash script that reads input from the user and validates if the inputted value exists (non-blank) and is an even integer. I'm using the terse test "$1" to test if input exists but combining it with other validation methods does not seem to work. My validation methods are like so:
readValidBookLength() {
BOOKLENGTH=$1
while ! [ isValidBookLength $BOOKLENGTH ] && ! [ isBookLengthNumeric $BOOKLENGTH ] && [isBookLengthEvenNumber $BOOKLENGTH]; do
echo -e 'Book length? (HINT: An even number!): \c'
read -r BOOKLENGTH
done
}
isValidBookLength() {
test "$1"
}
isBookLengthNumeric() {
echo "I GOT HERE!"
BOOKLENGTH=$1
echo "${BOOKLENGTH}"
reg='^[0-9]+$'
if ! [[ $BOOKLENGTH =~ $reg ]] ; then
return 1
else
return 0
fi
}
isBookLengthEvenNumber() {
echo "I GOT HERE 2!"
BOOKLENGTH=$1
echo "${BOOKLENGTH}"
if [ $((BOOKLENGTH%2)) -eq 0 ] ; then
return 0
else
return 1
fi
}
Is this pattern of seeking a valid input after multiple validations correct. What am I missing here?

You shouldn't put [ before the calls to your validation functions. [ is a short name for the test command. You also need to group all the tests together and negate the whole group:
while ! { isValidBookLength "$BOOKLENGTH" && isBookLengthNumeric $BOOKLENGTH && isBookLengthEvenNumber $BOOKLENGTH; }; do

It looks like you want the loop to continue to execute if any of the tests fail. That means you should use ||, not &&, to combine the tests.

Related

Shell Script logical operator for conditions

$i="500,600"
$j="600"
if[$i -ne $j]; then
#some line
else
#some line
fi
This if condition is not going inside.
this if condition fails. else is pass.
how is this possible
can someone help me on this
The trick is to consider the "[" sign as a command (in fact it is one indeed), whose last argument must be a "]". So you must ensure that there is a space after [ and all of its arguments go to the proper place. In your case:
if [ "$i" -ne "$j" ]
then
# some code
else
# some code
fi
Since [ is a command, you might want to omit the if structure and use logical operators, taking advantage of lazy evaluation. The following means the same:
[ "$i" -ne "$j" ] && {
echo "hello" ;
echo "world" ;
} || {
echo "bye bye" ;
echo "world" ;
}

if else statement is failing in shell script

I have a very simple shell script which is failing at if-else. And I am not able to understand what is wrong. I checked my syntax and indentation.
echo_usr()
{
read -p "Do you want to preserve $EIP_HOME/conf and $EIP_HOME/installer/.datastore? [Y/N] " usr_in
kill_java()
if [ "$usr_in" == "y*" ] || [ "$usr_in" == "Y*" ]; then
preserve_conf()
else
if [ "$usr_in" == "n*" ] || [ "$usr_in" == "N*" ]; then
reset_home_eip()
else
echo "Invalid input"
fi
fi
reset_db()
}
It is giving me the following error:
syntax error near unexpected token `else'
To call a function with no arguments, just use the name of the function. Empty parentheses are not necessary, and in fact are a syntax error. (Or, more precisely, it's part of the syntax for a function definition, and if you try to use it as a function call you'll get a syntax error message later -- if you're lucky.)
The idea is that a call to a shell function looks and acts like an invocation of an external program.
For example, change:
preserve_conf()
to
preserve_conf
(Using elif rather than else followed by if is a good idea, but it's not the cause of the problem you're seeing.)
There's another problem that you won't see until you get past the syntax error (thanks to Sam for pointing it out in a comment). This:
if [ "$usr_in" == "y*" ] || [ "$usr_in" == "Y*" ]; then
isn't going to work correctly; the == operator used by the [ / test built-in doesn't do wildcard matching. If you're using bash, you can use [[ rather than [, and you can also combine the y and Y cases into a single pattern:
if [[ "$usr_in" == [yY]* ]] ; then
...
elif [[ "$usr_in" == [nN]* ]] ; then
...
fi
If you don't have a shell that supports that syntax, a case statement might be your next best bet -- in fact that's probably even cleaner than the if version:
case "$usr_in" in
[yY]*)
...
;;
[nN]*)
...
;;
*)
...
;;
esac

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.

Why is this Bash script not changing the string's value?

I can't understand why userType is not changing.
I know for certain it's successfully reaching determineType, but it isn't changing the value to "bbb" when I try to print out userType later.
userType="aaa"
function determineType {
userType="bbb"
}
function checkUser {
cat users.csv | \
while read userLine; do
if [[ $userLine =~ .*$user.* ]]
then
determineType
echo "1"
fi
done
echo "0"
}
As soulseekah said in a comment, your while loop is executed in a subshell. Instead, do (and, as a benefit, you get rid of the useless use of cat):
userType="aaa"
determineType() {
userType="bbb"
}
checkUser() {
while read userLine; do
if [[ $userLine = *$user* ]]; then
determineType
return 1
fi
done < users.csv
return 0
}
Note. I also changed a few things:
got rid of the useless regexp since the same can be achieved with globbing,
used more common ways of defining functions in bash,
used return instead of echo for returning values: you'd run into the same problem again with an echo: you'd probably use your function checkUser in another subshell to obtain the value returned by the echo.
You are using a pipe, which launch the while .. do in a subshell.
Changing the value of a variable in a subshell won't affect the original variable
You should replace the:
function checkUser {
cat users.csv | \
while read userLine; do
if [[ $userLine =~ .*$user.* ]]
then
determineType
echo "1"
fi
done
echo "0"
}
with
function checkUser {
while read userLine; do
if [[ $userLine =~ .*$user.* ]]
then
determineType
echo "1"
fi
done < users.csv
echo "0"
}
(This also get rid of a Useless Use Of Cat)

Bash boolean expression and its value assignment

Is there a way to to evaluate a boolean expression and assign its value to a variable?
In most of the scripting languages there is way to evaluates e.g
//PHS
$found= $count > 0 ; //evaluates to a boolean values
I want similar way to evaluate in bash:
BOOL=[ "$PROCEED" -ne "y" ] ;
This is not working and tried other way but could not get a boolean value. IS there a way to
do this WITHOUT using IF ?
You could do:
[ "$PROCEED" = "y" ] ; BOOL=$?
If you're working with set -e, you can use instead:
[ "$PROCEED" = "y" ] && BOOL=0 || BOOL=1
BOOL set to zero when there is a match, to act like typical Unix return codes. Looks a bit weird.
This will not throw errors, and you're sure $BOOL will be either 0 or 1 afterwards, whatever it contained before.
I would suggest:
[ "$PROCEED" = "y" ] || BOOL=1
This has the advantage over checking $? that it works even when set -e is on. (See writing robust shell scripts.)
Rather than using ... && BOOL=0 || BOOL=1 suggested in the currently-accepted answer, it's clearer to use true and false.
And since this question is about bash specifically (not POSIX shell), it's also better to use [[ instead of [ (see e.g. 1 and 2), which allows using == instead of =.
So if you had to use a one-liner for something like this in bash, the following would be better:
[[ "$PROCEED" == "y" ]] && should_proceed=true || should_proceed=false
Then you can use the derived variable ergonomically in boolean contexts...
if $should_proceed; then
echo "Proceeding..."
fi
...including with the ! operator:
if ! $should_proceed; then
echo "Bye for now."
exit 0
fi
Assignment:
found=$((count > 0))
For a boolean test:
BOOL=$(test "$PROCEED" = y && echo true || echo false)
In general, a
x=$(...)
assigns the output of ... to the variable x. The y does not need quotes, because it contains nothing which needs to be masked.
A -ne is used for arithmetic comparison; see help test for an overview and quick reminder.
As explained in the accepted answer, the return value seems odd as true will return 0 and false 1. To make it easier to understand:
#!/bin/bash
test=$( [[ $1 == "y" ]]; echo $(($? == 0)) )
echo "$test"
# It will print "1", otherwise "0".
# To use it in conditions:
if [ $test ]; then
...
fi
Another way is:
test=$( [[ $1 == "y" ]] && echo "true" || echo "false" )
# In this case `[]` are not required:
if $test; then
...
fi

Resources