- Kernel module check if file exists
- Linux / UNIX: Find Out If File Exists With Conditional Expressions in a Bash Shell
- Syntax to find out if file exists with conditional expressions in a Bash Shell
- Find out if file /etc/passwd file exist or not
- How can I tell if a regular file named /etc/foo does not exist in Bash?
- [[ example
- Find out if directory /var/logs exist or not
- [[ example
- Are two files are the same?
- How to check if a file exists in a shell script
- A complete list for file testing in bash shell
- Conclusion
- How to properly check if file exists in Bash or Shell (with examples)
- 1. Bash/Shell: Check if file exists and is a regular file
- 1.1: Method-1: Using single or double brackets
- 1.2: Method-2: Using test command
- 1.3: Method-3: Single line
- 2. Bash/Shell: Check if file exists (is empty or not empty)
- 2.1: Method-1: Using single or double brackets
- 2.2: Method-2: Using test command
- 2.3: Method-3: Single line
- 3. Bash/Shell: Check if directory exists
- 3.1: Method-1: Using double or single brackets
- 3.2: Method-2: Using test command
- 3.3: Method-3: Single line
- 4. Bash/Shell: Check if directory exists (empty or not empty)
- 4.1: Method-1: List the directory content and verify
- 4.2: Method-2: Using find command
- 4.3: Method-3: List the content
- 5. Bash/Shell: List of attributes to test file
- Conclusion
- Related Posts
Kernel module check if file exists
I’m making some extensions to the kernel module nandsim, and I’m having trouble finding the correct way to test if a file exists before opening it. I’ve read this question, which covers how the basic open/read/write operations go, but I’m having trouble figuring out if and how the normal open(2) flags apply here.
I’m well aware that file reading and writing in kernel modules is bad practice; this code already exists in the kernel and is already reading and writing files. I am simply trying to make a few adjustments to what is already in place. At present, when the module is loaded and instructed to use a cache file (specified as a string path when invoking modprobe), it uses filp_open() to open the file or create it if it does not exist:
You might ask, «what do you really want to do here?» I want to include a header for the cache file, such that it can be reused if the system needs to be reset. By including information about the nand page geometry and page count at the beginning of this file, I can more readily simulate a number of error conditions that otherwise would be impossible within the nandsim framework. If I can bring down the nandsim module during file operations, or modify the backing file to model a real-world fault mode, I can recreate the net effect of these error conditions. This would allow me to bring the simulated device back online using nandsim, and assess how well a fault-tolerant file system is doing its job.
My thought process was to modify it as follows, such that it would fail trying to force creation of a file which already exists:
What I’m seeing is an error, but it is not the one I would have expected. It is reporting errno 14, EFAULT (bad address) instead of errno 17 EEXIST (File exists). I don’t want to run with this because I would like this to be as idiomatic and correct as possible.
Is there some other way I should be doing this?
Do I need to somehow specify that the file path is in user address space? If so, why is that not the case in the code as it was?
EDIT: I was able to get a reliable error by trying to open with only O_RDWR and O_LARGEFILE , which resulted in ENOENT . It is still not clear why my original approach was incorrect, nor what the best way to accomplish my goal is. That said, if someone more experienced could comment on this, I can add it as a solution.
Источник
Linux / UNIX: Find Out If File Exists With Conditional Expressions in a Bash Shell
W ith the help of BASH shell and IF command, it is possible to find out if a file exists or not on the filesystem. A conditional expression (also know as “evaluating expressions”) can be used by [[ compound command and the test ( [ ) builtin commands to test file attributes and perform string and arithmetic comparisons.
You can easily find out if a regular file does or does not exist in Bash shell under macOS, Linux, FreeBSD, and Unix-like operating system. You can use [ expression ] , [[ expression ]] , test expression , or if [ expression ]; then . fi in bash shell along with a ! operator. Let us see various ways to find out if a file exists or not in bash shell.
Syntax to find out if file exists with conditional expressions in a Bash Shell
The general syntax is as follows:
[ parameter FILE ]
OR
test parameter FILE
OR
[[ parameter FILE ]]
Where parameter can be any one of the following:
- -e : Returns true value if file exists.
- -f : Return true value if file exists and regular file.
- -r : Return true value if file exists and is readable.
- -w : Return true value if file exists and is writable.
- -x : Return true value if file exists and is executable.
- -d : Return true value if exists and is a directory.
Please note that the [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells. Let us see some examples.
Find out if file /etc/passwd file exist or not
Type the following commands:
$ [ -f /etc/passwd ] && echo «File exist» || echo «File does not exist»
$ [ -f /tmp/fileonetwo ] && echo «File exist» || echo «File does not exist»
How can I tell if a regular file named /etc/foo does not exist in Bash?
You can use ! operator as follows:
[ ! -f /etc/foo ] && echo «File does not exist» Exists
OR
[[ example
Enter the following commands at the shell prompt:
$ [[ -f /etc/passwd ]] && echo «File exist» || echo «File does not exist»
$ [[ -f /tmp/fileonetwo ]] && echo «File exist» || echo «File does not exist»
Find out if directory /var/logs exist or not
Type the following commands:
$ [ -d /var/logs ] && echo «Directory exist» || echo «Directory does not exist»
$ [ -d /dumper/fack ] && echo «Directory exist» || echo «Directory does not exist»
[[ example
$ [[ -d /var/logs ]] && echo «Directory exist» || echo «Directory does not exist»
$ [[ -d /dumper/fake ]] && echo «Directory exist» || echo «Directory does not exist»
Are two files are the same?
Use the -ef primitive with the [[ new test command:
How to check if a file exists in a shell script
You can use conditional expressions in a shell script:
Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf
To check if a file exists in a shell script regardless of type, use the -e option:
You can use this technique to verify that backup directory or backup source directory exits or not in shell scripts. See example script for more information.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
A complete list for file testing in bash shell
From the test command man page:
[ Expression ] | Meaning |
---|---|
-b filename | Return true if filename is a block special file. |
-c filename | Return true if filename exists and is a character special file. |
-d filename | Return true filename exists and is a directory. |
-e filename | Return true filename exists (regardless of type). |
-f filename | Return true filename exists and is a regular file. |
-g filename | Return true filename exists and its set group ID flag is set. |
-h filename | Return true filename exists and is a symbolic link. This operator is retained for compatibility with previous versions of this program. Do not rely on its existence; use -L instead. |
-k filename | Return true filename exists and its sticky bit is set. |
-n filename | Return true the length of string is nonzero. |
-p filename | Return true filename is a named pipe (FIFO). |
-r filename | Return truefilename exists and is readable. |
-s filename | Return true filename exists and has a size greater than zero. |
-t file_descriptor | Return true the filename whose file descriptor number is file_descriptor is open and is associated with a terminal. |
-u filename | Return true filename exists and its set user ID flag is set. |
-w filename | Return true filename exists and is writable. True indicates only that the write flag is on. The file is not writable on a read-only file system even if this test indicates true. |
-x filename | Return true filename exists and is executable. True indicates only that the execute flag is on. If file is a directory, true indicates that file can be searched. |
-z string | Return true the length of string is zero. |
-L filename | Return true filename exists and is a symbolic link. |
-O filename | Return true filename exists and its owner matches the effective user id of this process. |
-G filename | Return true filename exists and its group matches the effective group id of this process. |
-S filename | Return true filename exists and is a socket. |
file1 -nt file2 | True if file1 exists and is newer than file2. |
file1 -ot file2 | True if file1 exists and is older than file2. |
file1 -ef file2 | True if file1 and file2 exist and refer to the same file. |
Conclusion
You just learned how to find out if file exists with conditional expressions in a Bash shell. For more information type the following command at shell prompt or see test command in our wiki or see bash man page here:
test(1)
Источник
How to properly check if file exists in Bash or Shell (with examples)
Table of Contents
In this tutorial I will cover different attributes you can use in bash or shell scripting to check against files and directories. You can use bash conditional expressions with [[ ]] or use test with [ ] to check if file exists.
We will be using bash if and else operator for all the examples so I would recommend you to read: Bash if else usage guide for absolute beginners
1. Bash/Shell: Check if file exists and is a regular file
This section shows the examples to check if regular file exists in bash.
1.1: Method-1: Using single or double brackets
Using double brackets [[..]]
Using single brackets [..]
1.2: Method-2: Using test command
test command is used to check file types and compare values.
1.3: Method-3: Single line
We can use single or double brackets here in this example. I would recommend always to use double brackets when you are writing one liner code in shell as it minimises the risk of getting warnings on the console when word splitting takes place.
The statement after && will be executed if SUCCESS. If the first condition returns FALSE then statement with || will be executed.
Similarly using test command to check if regular file exists in bash or shell script in single line.
2. Bash/Shell: Check if file exists (is empty or not empty)
To check if the file exists and if it is empty or if it has some content then we use » -s » attribute
2.1: Method-1: Using single or double brackets
Check if file exists and empty or not empty using double brackets [[..]]
Check if file exists and empty or not empty using double brackets [..]
2.2: Method-2: Using test command
Using test command we combine -s attribute to check if file exists and is empty or has some content:
2.3: Method-3: Single line
We can use both double or single brackets for such one liner but as I said earlier I would recommend using double brackets.
Similarly with test command we can use && and || operator to check the file in single line command inside our shell script.
3. Bash/Shell: Check if directory exists
I hope you know that in Linux everything is a file. So in that way, a directory is also considered to be a file. We can use » -d » attribute to check if a directory exists in shell programming.
3.1: Method-1: Using double or single brackets
We can use -d attribute within single [..] or double brackets [[..]] to check if directory exists.
Similarly we use single brackets in this example to check if the directory is preset within shell script.
3.2: Method-2: Using test command
In this example we will use test command to make sure if directory is present or not before we perform certain task.
3.3: Method-3: Single line
In this example we will use single and double brackets in single line form to check for the directory. The statement after && operator will be executed if the first condition is TRUE and if it is FALSE the || condition’s statement will be executed.
I would recommend using [[..]] instead of [..] for such one liner codes in shell programming.
Similarly with && and || we can use test command to check if directory exists
4. Bash/Shell: Check if directory exists (empty or not empty)
There are no shell attributes as I have used in all other examples and scenarios in this tutorial. But we do have some hacks which we can use to check if directory is empty or not- empty.
4.1: Method-1: List the directory content and verify
In this example we will list the content of the directory, suppress the output and then based on the exit code check if the directory is empty or contains some content
We can also reverse this by putting a NOT ( ! ) condition. So it would look like:
The output would be same in both the example scripts.
4.2: Method-2: Using find command
We can use find command and then suppress the output to check if the target directory has some content or not.
4.3: Method-3: List the content
Again as I said since there is no easy way to check if a directory is empty or not using some attributes, we will list the content of the directory. If you get no output then the directory is empty or else not empty
5. Bash/Shell: List of attributes to test file
Similarly there are many more attributes which you can use with shell scripts to check for different file types, such as symbolic links, file permissions etc.
Attributes | What it does? |
---|---|
-a FILE | True if FILE exists |
-b FILE | True if FILE exists and is a block special file. |
-c FILE | True if FILE exists and is a character special file. |
-d FILE | True if FILE exists and is a directory. |
-e FILE | True if FILE exists |
-f FILE | True if FILE exists and is a regular file |
-g FILE | True if FILE exists and its set-group-id bit is set |
-h FILE | True if FILE exists and is a symbolic link |
-k FILE | True if FILE exists and its «sticky» bit is set |
-p FILE | True if FILE exists and is a named pipe (FIFO) |
-r FILE | True if FILE exists and is readable |
-s FILE | True if FILE exists and has a size greater than zero |
-u FILE | True if FILE exists and its set-user-id bit is set |
-w FILE | True if FILE exists and is writable |
-x FILE | True if FILE exists and is executable |
-G FILE | True if FILE exists and is owned by the effective group id |
-L FILE | True if FILE exists and is a symbolic link |
-N FILE | True if FILE exists and has been modified since it was last read |
-o FILE | True if FILE exists and is owned by the effective user id |
-S FILE | True if FILE exists and is a socket |
FILE1 -ef FILE2 | True if FILE1 and FILE2 refer to the same device and inode numbers |
FILE1 -nt FILE2 | True if FILE1 is newer (according to modification date) than FILE2 , or if FILE1 exists and FILE2 does not |
FILE1 -ot FILE2 | True if FILE1 is older than FILE2 , or if FILE2 exists and FILE1 does not |
Conclusion
In this tutorial I shared brief examples of test operators to check for files and directories. You can use any attribute from the table I have shared to enhance your script execution with proper tests.
Lastly I hope the steps from the article to check if file exists or not on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник