I use this little script in some of my larger bash scripts and thought I would share:
Usage: ./file.sh <filename>Code:#!/bin/bash # Check if a file exists # # Usage: ./file.sh <filename> # if [ -f $1 ] then echo "$1 file exists" else echo "$1 file does not exist" fi
Example:
Output:Code:# ./file.sh test
./file.sh test
Code:test file exists
-e checks if a file exist too.
What does -e and -f even mean?
Those options belong to test.
Run man test and you'll see a list of possible options and its meanings.
In shell script the [ ] indicate a test so you can omit the word test.Code:if [ -f $1 ]
Oh, I see. There are several options that test a file for bash scripting:
Code:FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and read permission is granted -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and write permission is granted -x FILE FILE exists and execute (or search) permission is granted
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks