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: