Linux bash if string empty

Test if a command outputs an empty string

A command does not return a string (it returns a small integer exit code, usually 0 for success and 1 or 2 on failure), but it may output some data, to put in a string.

@BasileStarynkevitch this is the thing I need.I know command returns exit code.But my commands exit code is always 0.so I need to control the output

13 Answers 13

Previously, the question asked how to check whether there are files in a directory. The following code achieves that, but see rsp’s answer for a better solution.

Empty output

Commands don’t return values – they output them. You can capture this output by using command substitution; e.g. $(ls -A) . You can test for a non-empty string in Bash like this:

if [[ $(ls -A) ]]; then echo "there are files" else echo "no files found" fi 

Note that I’ve used -A rather than -a , since it omits the symbolic current ( . ) and parent ( .. ) directory entries.

Note: As pointed out in the comments, command substitution doesn’t capture trailing newlines. Therefore, if the command outputs only newlines, the substitution will capture nothing and the test will return false. While very unlikely, this is possible in the above example, since a single newline is a valid filename! More information in this answer.

Exit code

If you want to check that the command completed successfully, you can inspect $? , which contains the exit code of the last command (zero for success, non-zero for failure). For example:

files=$(ls -A) if [[ $? != 0 ]]; then echo "Command failed." elif [[ $files ]]; then echo "Files found." else echo "No files found." fi 

Источник

Bash: How to Check if String is Not Empty

One of these days, you may experience it. Sometimes, a bash script may contain empty variables. Here, we have provided every detail on how to check for empty variables in a bash script, as well as introduce a handy freeware for managing Linux partitions on Windows PC.

  • bash command if a string is not empty
  • examples of the check
  • when DiskInternals can help you

Variables that are set and not empty

A variable is either defined or not defined. However, when a variable is defined but has no value, then the variable is “Not Set.” Similarly, when a variable is defined and has a value, then it is “Set.” Thus, declared variable but no value equals to “Not Set,” and declared variable with value equals to “Set.”

Читайте также:  How to install all packages in linux

In programming, it is essential to check if a variable is “set” or “not set,” which means you have to check if a bash script variable has a value or not. This check helps for effective data validation. However, there’s no built-in function for checking empty variables in bash scripts, but bash supports a feature that can help out.

-n operator

-n is one of the supported bash string comparison operators used for checking null strings in a bash script. When -n operator is used, it returns true for every case, but that’s if the string contains characters. On the other hand, if the string is empty, it won’t return true.

n operator to check if string is not empty

-z operator

-z is the second supported bash string comparison operator used to check if a string is empty or not. The -z operator functions similarly like -n operator. Below is an example:

n operator to check if string is empty

Most importantly, you should add spaces around the square brackets. If there are no spaces, bash will complain about that. Also, since any bash test without an argument will always return true, it is advisable to quote the variables so that the test will have at least an (empty) argument, irrespective of whether the variable is set or not.

Check to see if a variable is empty or not

Create a new bash file, named, and enter the script below.

Check to see if a variable is empty or not

The script above stores the first command-line argument in a variable and then tests the argument in the next statement.

This script will print the first argument because it is not empty. However, the output would be “First argument is empty” if nothing is contained in the argument.

How to access Linux files from Windows?

The program is available for free, and it supports quite a couple of handy features.

Linux Shell ZSH Bash Perl Ext2/Ext3/Ext4 Arch Linux Systemd New Mount a drive Got error or failure How to

  • About a bash date command
  • Bash and sh: is there any difference
  • About Bash Language
  • Guide in Pictures
  • Shell script usage
  • Bash: A Script For User Input
  • Here is everything you need to know about Bash for Windows
  • Bash Script SSH: How to Use It
  • How to use bash get script directory in Linux
  • Copy command in shell scripts
  • Learn about a bash error code
  • 5 Basic Shell Script Examples for Your First Script
  • How to Check Bash String Equality
  • How to Use Linux Wait Command
  • Bash: How to Loop Through Files in Directory
  • 20 Examples of Bash Find Command
  • Bash Cat Command in Examples
  • Linux ZSH: the basic you need to know
  • Shell Script Cut: Basic You Need to Know
  • Basic of Grep in Linux Shell Script
  • Bash: how to split strings in Linux
  • An Algorithm: How to Create Bash While Loop
  • Bash Time Command on Linux
  • Bash: How to Check if the File Does Not Exist
  • How to Use Shell Script Sleep Command
  • Linux Shell: What You Need to Know at First
  • Bash Script: All You Need to Know
  • Mount Linux Drive on Windows for Free
  • How to Mount Ext4 on Windows for Free
  • How to Access Ext4 from Windows
  • How to Access Linux Ext2 or Ext3 on Windows
  • Linux: Sudo in Bash Scripts
  • A Linux bin/bash Shell
  • Linux: Bash Printf Examples
  • Linux: Bash First Line
  • Linux: Write a Shell Script
  • Linux: A Bash Source Command
  • A Bash to Loop through Lines in File
  • A Bash Test Command
  • A Bash‌ ‌Status‌ ‌of‌ Last‌ ‌Command‌
  • Linux: New Line in Shell Script
  • Linux: $0 in a Shell Script
  • Linux: A Bash Startup Script
  • A Bash Multiline Command
  • A Bash Dirname Command
  • Linux: A Bash Linter
  • A Bash Nested Loop
  • Use a Shell Script to Send an Email
  • Hello World Script in Bash
  • A crontab service shell script
  • Linux: A Bash Basename Command
  • Using Bash to Write to a File
  • AWK in a Bash Script
  • Learn about systemd startup script
  • About chaining bash commands
  • Using a bash tee command
  • Learn about useful bash scripts
  • Bash for Loop in One Line
  • Learn about a bash wait command
  • Arch Linux install script
  • About advanced bash scripting
  • To run a shell script in Dockerfile
  • About a bash export command
  • About a bash UNTIL loop
  • Using /usr/bin/env command
  • Learn about Korn shell scripting
  • Shell Script: Replace String in File
  • Linux: Bash String Ends With
  • Whether bash waits for command to finish
  • Using bash if 0
  • Using && in an IF statement in bash
  • If you want to run shell script in background
  • The disk you inserted was not readable by this computer error
  • Learn about C shell script
  • Learn about SFTP in bash scripting
  • Install Oracle Database
  • Examples of using the Expect
  • Learn to run Perl script in Linux
Читайте также:  Building linux kernel driver

Источник

bash if empty string

when you press enter its like its the same as when you type «Y» or «y» So i was wondering how to make that in bash This is what i have so far?

echo "question?[Y/n]" read choose if [ $choose ~= "Y" ] [ $choose ~= "y" ] [ $choose ~= "" ] then #code fi 

4 Answers 4

Classically (meaning it will work in POSIX-ish shells other than bash ), you’d write:

echo "Question? [Y/n]" read choose if [ "$choose" = "Y" ] || [ "$choose" = "y" ] || [ -z "$choose" ] then # code fi 

The quotes ensure that the test operator see an argument even if $choose is an empty string.

The [[ operator seems to allow you to get away without quoting strings, but is not part of a POSIX shell. POSIX recognizes its existence by noting:

The following words may be recognized as reserved words on some implementations (when none of the characters are quoted), causing unspecified results:

If you want the shell to leave the cursor on the same line as the prompt, you can use:

POSIX shells recognize the \c escape; bash does not:

(There may be a way to make bash handle that, but printf is probably more portable.)

+1 for printf suggestion. It is much neat compared to echo (personal opinion) 🙂 «echo -n» would print the message and leave the cursor on the same line, e.g. echo -n «Question? [Y/n]»

@AshishKumar: Thanks. I remembered that bash follows the Unix 7th Edition Bourne shell using echo -n after I’d posted the answer, instead of the System III, System V style of escape with \c . See Bloated echo command for a discussion about styles of the echo command.

echo -n "Question? [Y/n]" read choose shopt -s nocasematch if [[ "$" =~ Y ]]; then # they said yes else # they said something else fi 

This approach has the possible advantage that it leaves $choose set to Y if you examine it later. If you prefer to be able to tell later whether they entered Y or just pressed enter, you can use $ instead.

Читайте также:  Установка линукс elementary os

If you’d rather not set nocasematch , you can always check explicitly for both Y and y . Or, if you like the nocasematch solution but care about preserving the state of the flag, you can check and restore it:

shopt -q nocasematch let not_set=$? shopt -s nocasematch 
if (( not_set )); then shopt -u nocasematch fi 

Источник

Оцените статью
Adblock
detector