Check if string is neither empty nor space in shell script
I am trying to run the following shell script which is supposed to check if a string is neither space nor empty. However, I am getting the same output for all the 3 mentioned strings. I have tried using the «[[» syntax as well but to no avail. Here is my code:
str="Hello World" str2=" " str3="" if [ ! -z "$str" -a "$str"!=" " ]; then echo "Str is not null or space" fi if [ ! -z "$str2" -a "$str2"!=" " ]; then echo "Str2 is not null or space" fi if [ ! -z "$str3" -a "$str3"!=" " ]; then echo "Str3 is not null or space" fi
# ./checkCond.sh Str is not null or space Str2 is not null or space
6 Answers 6
You need a space on either side of the != . Change your code to:
str="Hello World" str2=" " str3="" if [ ! -z "$str" -a "$str" != " " ]; then echo "Str is not null or space" fi if [ ! -z "$str2" -a "$str2" != " " ]; then echo "Str2 is not null or space" fi if [ ! -z "$str3" -a "$str3" != " " ]; then echo "Str3 is not null or space" fi
Thanks a lot, it works. But I wonder why the assignment doesn’t use a space whereas a comparison does.
^^It’s syntax. The first word on the command line is the command & subsequent ones are arguments. var=value [command [args]] is the syntax, in which a variable is assigned value. for comparison, [ ( /usr/bin/[ ) is the command & it requires var1, != & var2 to be 3 separate arguments. var1!=var2 is a single argument.
Bash Check If String Is Empty
While coding in any programming language, we use many variables of different types. One well-known and most used variable type is the “string”. The string is a group of characters and special symbols including space in programming. While working in Linux provides us the opportunity to utilize string variables in our code. Today, we will demonstrate some of the examples to check whether a string variable is empty or not using some of the most well-known Bash options.
So, let’s get started now. Let’s start with the Bash file creation, as all of our work will be done within the Bash file. So, use the “touch” instruction of Ubuntu to create a Bash file named “empty” with the “sh” extension. The GNU Nano editor can be utilized to open this newly created Bash file.
Example 01:
We will be starting from the most basic illustration of checking whether the string is empty or not. For this, we will be using the assignment operator within the “if-else” statement to state the condition. First, we have added a Bash support “#!/bin/bash” in our code file. After this, we have initialized an empty string variable “str” using the assignment operator and double inverted commas. Here, the “if-else” statement states our condition and its result according to the returned value.
We have started the “if” clause with square brackets to add our condition. We have been using the double inverted commas to state the string variable “str” with the “$” sign and utilizing the assignment operator “=” to check whether it’s empty or not. If the condition is satisfied, the “then” part of the statement will execute the echo statement stating that the string is “Empty”. Otherwise, the “else” part of the statement will run the “echo” statement stating that the string is “Not Empty”. The if-else statement ends at “fi”.
Save your code using “Ctrl+S” and quit this editor utilizing the Ctrl+X shortcut. Coming back to the terminal, we are using the Bash instruction to run this Bash file, i.e., empty.sh. On execution, it returns “Empty” because the string “str” is initialized empty in the code, and the “then” part of the “if-else” statement has been executed so far.
Example 02
Let’s look at another option, “-z”, used so far in Bash to check for the empty string. The code has been started with Bash support, and we have initialized a string variable “v” with the value “Hello” in it. Then, we started the “if-else” statement to check whether the string is empty. For this, we have used the “-z” option within the square brackets condition of the “if” part of the statement and stated the variable “V” with the “$” sign in inverted commas. If the condition is satisfied and the string is found empty, the “then” part will get executed, and the echo statement will display “String v is empty”. On the contrary, if the string is not empty, the else part will be executed, and the echo statement will display “String v is not Empty”.
After saving this file, we exited the editor and executed the code using the Bash query shown below. It turns out that the string is not empty, and the “else” part of the statement was executed. This shows that the “-z” option works perfectly fine to check for a string emptiness.
Example 03
Here is another option, “-n”, to check whether the specified string is empty or not. It works on the rule of checking the length of a string by counting the string characters in it. If the length of a particular string turns out to be other than zero, it will return “true”; otherwise, it will return “false”. Let’s get started with the use of the “-n” option in our illustration now. So, we have initialized an empty string variable “val” first. After this, we have been using the “-n” option within the “if” part of the “if-else” statement within the square brackets. This option is checking whether the length of variable “val” is other than zero or not. If the length of variable “val” is other than zero, the “-n” option will return true, and the “then” part of the statement will get executed.
The echo statement will display the message “String val is not Empty”. But, if the statement returns “false”, the else part will execute its echo statement and show the message “String val is empty”. As our string “val” is empty, we expect it to execute its else part.
When we have executed our code with Bash instruction after saving the code, we have the result as we expected, i.e., “String val is empty”.
Example 04
You can also use the “test” method to check for the string emptiness, as shown below. Within this method, you need to test the variable using the “$” sign before the curly brackets around the variable name “val”. Within the curly brackets, you need to use the variable name “val” and the keyword “test” separated from each other by “:” as shown. It will work the same as the previously explained options in the examples.
The following result will be shown according to the variable “val”.
Conclusion:
This article is all about using different options of Bash to check for the emptiness of some strings. We have created simple Bash scripts using the variables and if-else statements. Within the codes, we have used different options of Bash like “-n”, “-z”, and “=” assignment operators to check for the string emptiness. The results are displayed according to the cases. We hope you found this article helpful. Check the other Linux Hint articles for more tips and tutorials.
About the author
Omar Farooq
Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.
How do I test for an empty string in a Bash case statement?
I have a Bash script that performs actions based on the value of a variable. The general syntax of the case statement is:
case $ in start) do_start ;; stop) do_stop ;; config) do_config ;; *) do_help ;; esac
I’d like to execute a default routine if no command is provided, and do_help if the command is unrecognized. I tried omitting the case value thus:
case $ in ) do_default ;; . *) do_help ;; esac
syntax error near unexpected token `)'
case $ in ^$) do_default ;; . *) do_help ;; esac
3 Answers 3
The case statement uses globs, not regexes, and insists on exact matches.
So the empty string is written, as usual, as «» or » :
case "$command" in "") do_empty ;; something) do_something ;; prefix*) do_prefix ;; *) do_other ;; esac
Perhaps explain in your answer why $command is quoted? (But without «Edit:», «Update:», or similar — the answer should appear as if it was written today.)
@PeterMortensen: in shell scripting, what demands explanation is the absence of quotes; quoting expansions goes without saying. I could have left the quotes out, but I chose not to and thus didn’t have to explain why it’s possible to do so. (And I’m not actually 100% sure that no corner cases exist.)
I use a simple fall through. no parameters passed ($1=»») will be caught by the second case statement, yet the following * will catch any unknown parameter. Flipping the «») and *) will not work as *) will catch everything every time in that case, even blanks.
#!/usr/local/bin/bash # testcase.sh case "$1" in abc) echo "this $1 word was seen." ;; "") echo "no $1 word at all was seen." ;; *) echo "any $1 word was seen." ;; esac
Here’s how I do it (to each their own):
#!/bin/sh echo -en "Enter string: " read string > finder.txt echo "--" >> finder.txt for file in `find . -name '*cgi'` do x=`grep -i -e "$string" $file` case $x in "" ) echo "Skipping $file"; ;; *) echo "$file: " >> finder.txt echo "$x" >> finder.txt echo "--" >> finder.txt ;; esac done more finder.txt
If I am searching for a subroutine that exists in one or two files in a filesystem containing dozens of cgi files I enter the search term, e.g. ‘ssn_format’. bash gives me back the results in a text file (finder.txt) that looks like this:
— ./registry/master_person_index.cgi: SQLClinic::Security::ssn_format($user,$script_name,$local,$Local,$ssn) if $ssn ne «»;