0

I need to use an if statement to respond to a blank output. I've got:

while read -p "Enter filename:   "
do Extant=$(ls | grep $name)
echo "$Extant"

to store and display the results. that's fine... until a filename doesn't exist. I'd like for it to:

  1. test if $Extant is blank (indicating that that file doesn't exist),

  2. then echo something like "it's not here"

  3. then go back to the while loop

    or else

  4. just go back to the while loop (since it'll output the matching file, if it exists).

I initially figured, I could do this with something like:

if $Extant=""
then echo "it's not here"
return
else
return
fi

but that's not really turning out the way I had hoped. It keeps trying to run what it finds, as commands

Not sure what's going on here, But I appreciate any help

1

You don't want to use ls nor grep here. ls is primarily for visual inspection of directory contents, and grep is primarily for returning lines of text from larger texts.

IFS= read -r -p 'Filename please: ' name

while [[ ! -e $name ]]; do
    printf '%s does not exist\n' "$name"
    read -p 'Try again: ' name
done

printf '%s exists\n' "$name"

The -e test will be true if the given name exists in the filesystem. Here we negate the sense of that test in the loop.

To avoid two separate calls to read:

while true; do
    IFS= read -r -p 'Filename please: ' name

    [[ -e $name ]] && break

    printf '%s does not exist\n' "$name"
done

printf '%s exists\n' "$name"

This loop is exited with break whenever the given $name exists in the filesystem.

Note that neither of these variations will be able to read a filename that contains a newline (which would be valid in filenames on Unix systems).


It is usually more convenient for a user to give any filename as a command line argument to the script, which means they can use the shell's filename completion facilities or filename globbing patterns to provide the filename:

#!/bin/bash

name=$1

if [[ ! -e "$name" ]]; then
    printf '%s does not exist\n' "$name"
    exit 1
fi

printf '%s exists\n' "$name"

The above script expects to be run with a single filename as its only argument. A message will be printed relating to the existence of the given name. If the given name does not exist, the script will terminate within the if statement and the user would have to try again.

This variation would be able to take a filename containing a newline as we don't read the name as a string with read.


Related:

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.