How to check whether a variable is empty or contains some value?

hi,

i want to check whether a a variable contains some value or is empty in a shell script. so if the variable contains some value i want to do some job and if the variable doesnt contain any value then i need to skip that job.

here is a sample script

read_filenames.sh contains

FILENAME=$1

FILE="s1.txt"

if [ -n $FILENAME ]; then

      FILE=$FILENAME

fi

echo "FILE = {$FILE}"

so, when i run the script without passing any argument, variable "FILE" should contain "s1.txt". so the output should be

$ sh read_filenames.sh

FILE = {s1.txt}

but when i pass an argument to the script, then the variable "FILE" should contain the argument value. so the output should be

$ sh read_filenames.sh p1.txt

FILE = {p1.txt}

currently i am using the above code, but if i dnt pass any argument to the script. the output is

FILE = {}

i read somewhere that

if [ -n $FILENAME ]; then

checks whether the variable is empty or not. but i dnt think that its doing that job. can anyone tell how can i do the above.

Try:

FILENAME="s1.txt"

FILE=${1:-$FILENAME}

printf 'FILE = {%s}\n' "$FILE"
1 Like
FILE=${1:-s1.txt}
echo $FILE
1 Like

ya it works fine.. Can you explain me.

FILE=${1:-$FILENAME}

or

FILE=${1:-s1.txt} 

If $1 is empty, then ${1:-s1.txt} expands to "s1.txt". It's like telling, if $1 is empty use the default value "s1.txt" instead.

$FILENAME is nothing but "s1.txt". So, both the approaches mean the same thing.

2 Likes

In your original script snippet, replace -n (non-zero check) with -z (zero check), and it will fly. man bash :