File System Operations in Shell

LinuxLinuxBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to perform various file tests in the shell. File tests are useful for checking the properties of files and directories in the file system. You will familiarize yourself with common file test commands and their usage.

Test if a file exists

To test if a file exists, you can use the -e command. This command checks if a file exists as a regular file or a directory.

If the file exists, it will return true; otherwise, it will return false.

#!/bin/bash
filename="sample.md"
if [ -e "$filename" ]; then
  echo "$filename exists as a file"
fi

Cearate a file called ~/project/file.sh.

cd ~/project
chmod +x file.sh
./file.sh

Then, create a file called ~/project/sample.md.

cd ~/project
touch sample.md

Re-run the script.

./file.sh
sample.md exists as a file

Test if a directory exists

To test if a directory exists, you can use the -d command. This command checks if a directory exists. If the directory exists, it will return true; otherwise, it will return false.

#!/bin/bash
directory_name="test_directory"
if [ -d "$directory_name" ]; then
  echo "$directory_name exists as a directory"
fi

Cearate a file called ~/project/directory.sh.

cd ~/project
chmod +x directory.sh
./directory.sh

Then, create a directory called ~/project/test_directory.

cd ~/project
mkdir test_directory

Re-run the script.

./directory.sh
test_directory exists as a directory

Test if a file is readable

To test if a file has read permission for the user running the script, you can use the -r command. This command checks if a file is readable. If the file is readable, it will return true; otherwise, it will return false. If the file doesn't exist, you can create it using the touch command.

#!/bin/bash
filename="sample.md"
if [ ! -f "$filename" ]; then
  touch "$filename" ## Create the file if it doesn't exist
fi
if [ -r "$filename" ]; then
  echo "You are allowed to read $filename"
else
  echo "You are not allowed to read $filename"
fi

Cearate a file called ~/project/readable.sh.

cd ~/project
chmod +x readable.sh
./readable.sh
You are allowed to read sample.md

Then, change the file permissions to remove the read permission.

cd ~/project
chmod -r sample.md

Re-run the script.

./readable.sh
You are not allowed to read sample.md

Summary

In this lab, you learned how to perform file tests in the shell. You learned how to test if a file exists, if a directory exists, and if a file is readable. File tests are essential for checking the properties of files and directories in the file system.

Other Linux Tutorials you may like