user258030
user258030

Reputation: 305

bash if statement to detect blank text

Hello i am currently trying to make an if statement within shell script to detect if the user has no inputted any text.

i would like if the user hasnt entered anythign or if what they entered is invalid to echo and alert until they type in something correct.

here is what i have so far

echo "Current Address books "
        ls -R |grep .txt
        echo "--------------------------------------------------------------------"
        echo -n  "Please Enter the file you want to search in: "
        read fileName
        book=$fileName
        if [ $fileName == "" ]
        then
                echo "Please Enter some Text "
        else
                echo -n "Please Enter a name: "
        read search

        grep -i $search $fileName

        if grep -q "$search" "$fileName";
        then
                echo "Found!"
        else
                echo "Not Found!"
        fi

fi

Upvotes: 2

Views: 225

Answers (3)

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

Something like this?

#!/bin/bash

echo "Current Address books "
find -name '*.txt' -type f -exec bash -c 'printf "%s\n" "${@#./}"' _ {} + # Don't parse the output of ls
printf -v spacesep "%68s"; printf '%s\n' "${spacesep// /-}"
fileName=
while [[ -z $fileName ]]; do
    read -rep "Please Enter the file you want to search in: " fileName
    book=$fileName # Is this variable used?
    # Check that the file is really a file
    if [[ -n $fileName ]] && [[ ! -f $fileName ]]; then
      echo "Not a file, try again"
      fileName=
    fi
done
search=
while [[ -z $search ]]; do
    read -rep "Please Enter a name: " search
    grep -i -- "$search" "$fileName"
done
if grep -qi -- "$search" "$fileName"; then
   echo "Found!"
else
   echo "Not Found!"
fi

Bonus. With the -e switch to read you have readline editing capabilities, and tab completion on files. Wooow!

Upvotes: 1

user3554425
user3554425

Reputation:

You can use a control loop

until [  $fileName != "" ]; do
     echo "Please Enter some Text " ;
     read -p "Please Enter a name: " fileName ;
done

Upvotes: 1

anubhava
anubhava

Reputation: 784928

You can use -z "$var" notation:

if [ -z "$fileName" ]; then
   echo "Please Enter some Text "
else
   read -p "Please Enter a name: " search
fi

to check if string length is zero.

Alternatively you can do this check using quoted variable name:

if [ "$fileName" == "" ]; then
   echo "Please Enter some Text "
else
   read -p "Please Enter a name: " search
fi

Upvotes: 1

Related Questions