Checking it see if a file exists in a script
Solution 1:
If you need a shell script then you can use this:
#!/bin/bash
file="$1"
if [ -f "$file" ]; then
echo "File $file exists."
else
echo "File $file does not exist."
fi
You can run it like this:
bash test.sh /tmp/bobv2.txt
Solution 2:
There's plenty of ways to perform a check on whether or not a file exists.
- use
test
command ( aka[
) to do[ -f /path/to/file.txt ]
-
use redirection to attempt to open file ( note that this isn't effective if you lack permissions to read the said file)
$ bash -c 'if < /bin/echo ;then echo "exists" ; else echo "does not exist" ; fi' exists $ bash -c 'if < /bin/noexist ;then echo "exists" ; else echo "does not exist" ; fi' $ bash: /bin/noexist: No such file or directory does not exist
or with silencing the error message:
$ 2>/dev/null < /etc/noexist || echo "nope" nope
-
use external program such as
stat
$ if ! stat /etc/noexist 2> /dev/null; then echo "doesn't exist"; fi doesn't exist
or
find
command:$ find /etc/passwd /etc/passwd $ find /etc/noexist find: ‘/etc/noexist’: No such file or directory