Linux check files in directory

How to properly check if file exists in Bash or Shell (with examples)

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

#!/bin/bash FILE="/etc/passwd" if [[ -f $FILE ]];then echo "$FILE exists" else echo "$FILE doesn't exist" fi
#!/bin/bash FILE="/etc/passwd" if [ -f $FILE ];then echo "$FILE exists" else echo "$FILE doesn't exist" fi

1.2: Method-2: Using test command

test command is used to check file types and compare values.

#!/bin/bash FILE="/etc/passwd" if test -f $FILE; then echo "$FILE exists" else echo "$FILE missing" fi

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.

#!/bin/bash FILE="/etc/passwd" [[ -f $FILE ]] && echo "$FILE exists" || echo "$FILE missing"

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.

#!/bin/bash FILE="/etc/passwd" test -f $FILE && echo "$FILE exists" || echo "$FILE missing"

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 [[..]]

#!/bin/bash FILE="/etc/passwd" if [[ -s $FILE ]]; then echo "$FILE exists and not empty" else echo "$FILE doesn't exist or is empty" fi

Check if file exists and empty or not empty using double brackets [..]

if [ -s $FILE ]; then echo "$FILE exists and not empty" else echo "$FILE doesn't exist or is empty" fi

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:

#!/bin/bash FILE="/etc/passwd" if test -s $FILE; then echo "$FILE exists and not empty" else echo "$FILE doesn't exist or is empty" fi

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.

#!/bin/bash FILE="/etc/passwd" test -s $FILE && echo "$FILE exists and not empty" || echo "$FILE doesn't exist or is empty"

Similarly with test command we can use && and || operator to check the file in single line command inside our shell script.

#!/bin/bash FILE="/etc/passwd" [[ -s $FILE ]] && echo "$FILE exists and not empty" || echo "$FILE doesn't exist or is empty"

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.

Читайте также:  Удаление маршрута route linux

3.1: Method-1: Using double or single brackets

We can use -d attribute within single [..] or double brackets [[..]] to check if directory exists.

#!/bin/bash DIR color: #f79c9c;">/var/log" if [[ -d $DIR ]]; then echo "$DIR exists" else echo "$DIR doesn't exist" fi

Similarly we use single brackets in this example to check if the directory is preset within shell script.

#!/bin/bash DIR color: #f79c9c;">/var/log" if [ -d $DIR ]; then echo "$DIR exists" else echo "$DIR doesn't exist" fi

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.

#!/bin/bash DIR color: #f79c9c;">/var/log" if test -d $DIR; then echo "$DIR exists" else echo "$DIR doesn't exist" fi

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.

#!/bin/bash DIR color: #f79c9c;">/var/log" [[ -d $DIR ]] && echo "$DIR exists" || echo "$DIR doesn't exist"

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

#!/bin/bash DIR color: #f79c9c;">/var/log" test -d $DIR && echo "$DIR exists" || echo "$DIR doesn't exist"

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

#!/bin/bash DIR color: #f79c9c;">/tmp" if ls -1qA $DIR | grep -q . ; then echo "$DIR is not -empty" else echo "$DIR is empty" fi

We can also reverse this by putting a NOT ( ! ) condition. So it would look like:

#!/bin/bash DIR color: #f79c9c;">/tmp" if ! ls -1qA $DIR | grep -q . ; then echo "$DIR is empty" else echo "$DIR is not-empty" fi

The output would be same in both the example scripts.

Читайте также:  Какая самая последняя версия linux

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.

#!/bin/bash DIR color: #f79c9c;">/tmp" if find -- "$DIR" -prune -type d -empty | grep -q . ; then echo "$DIR is empty" else echo "$DIR is not-empty" fi

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

#!/bin/bash DIR color: #f79c9c;">/tmp" if [[ -z "$(ls -A -- "$DIR")" ]] ; then echo "$DIR is empty" else echo "$DIR is not-empty" fi

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
Читайте также:  Linux in cloud computing

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.

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.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Check whether a certain file type/extension exists in directory [duplicate]

Counting lines is parsing. And it will return an incorrect number if any files contain \n (and yes, that is valid in file names).

Pray tell us then, what magical character would have to be in a file’s name in order to make the line count naught?

#/bin/bash myarray=(`find ./ -maxdepth 1 -name "*.py"`) if [ $ -gt 0 ]; then echo true else echo false fi 

+1 for wrapping subshell running find in parenthesis to make myarray an array variable. Otherwise, if find returns no result $ equals 1

This uses ls(1), if no flac files exist, ls reports error and the script exits; othewise the script continues and the files may be be processed

#! /bin/sh ls *.flac >/dev/null || exit ## Do something with flac files here 
shopt -s nullglob if [[ -n $(echo *.flac) ]] # or [ -n "$(echo *.flac)" ] then echo true fi 
#!/bin/bash files=$(ls /home/somedir/*.flac 2> /dev/null | wc -l) if [ "$files" != "0" ] then echo "Some files exists." else echo "No files with that extension." fi 

You need to be carful which flag you throw into your if statement, and how it relates to the outcome you want.

If you want to check for only regular files and not other types of file system entries then you’ll want to change your code skeleton to:

if [ -f file ]; then echo true; fi 

The use of the -f restricts the if to regular files, whereas -e is more expansive and will match all types of filesystem entries. There are of course other options like -d for directories, etc. See http://tldp.org/LDP/abs/html/fto.html for a good listing.

As pointed out by @msw, test (i.e. [ ) will choke if you try and feed it more than one argument. This might happen in your case if the glob for *.flac returned more than one file. In that case try wrapping your if test in a loop like:

for file in ./*.pdf do if [ -f "$" ]; then echo 'true'; break fi done 

This way you break on the first instance of the file extension you want and can keep on going with the rest of the script.

Источник

Оцените статью
Adblock
detector