Home >Operation and Maintenance >Linux Operation and Maintenance >Bash Shell: Test if a file or directory exists

Bash Shell: Test if a file or directory exists

不言
不言Original
2019-03-22 16:03:135782browse

When using bash programming, we often need to check whether the file already exists, create a new file, and insert data into the file. Sometimes we also need to execute other scripts from other scripts. This article will introduce about Bash Shell: testing whether a file or directory exists.

Bash Shell: Test if a file or directory exists

1. bash shell: Test whether the file exists

If we need to add some content or create a file from a script. First, make sure the file already exists. For example, one of my scripts creates a log in file/tmp/testfile.log and we need to make sure that file exists.

#!/bin/bash
 
if [ -f /tmp/testfile.log ]
then
    echo "File exists"
fi

The above statement can also be written using the test keyword, as shown below

#!/bin/bash
 
if test -f /tmp/testfile.log
then
    echo "File exists"
fi

Or we can write it in one line as shown below. This is very useful when writing shell scripts.

[ -f /tmp/testfile.log ] && echo "File exists"

Add other parts to the above command

[ -f /tmp/testfile.log ] && echo "File exists" || echo "File not exists"

2. bash shell: test whether the directory exists

Sometimes we need to Create a file in a directory, or a directory is required. We should all make sure that directory exists. For example, we now check if /tmp/mydir exists.

#!/bin/bash
 
if [ -d /tmp/mydir ]
then
    echo "Directory exists"
fi

The above statement can also be written using the test keyword, as shown below

#!/bin/bash
 
if test -d /tmp/mydir
then
    echo "Directory exists"
fi

Or we can write it in one line as shown below

[ -d /tmp/mydir ] && echo "Directory exists"

3, Bash Shell: Create file directory if not present

This is the best way to check if a file exists before creating it, otherwise you may receive an error message. This is useful when creating files or directories required by a shell script at runtime.

File:

[ ! -f /tmp/testfile.log ] && touch /tmp/testfile.log

Directory:

1    [ ! -d /tmp/mydir ] && mkdir -p /tmp/mydir

This article is all over here. For more other exciting content, you can pay attention to PHP Chinese Net's Linux Tutorial Video column!

The above is the detailed content of Bash Shell: Test if a file or directory exists. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn