Introduction to File and Directory Error Handling

Welcome! In this lesson, we will focus on error handling when dealing with files and directories in shell scripts. Managing file and directory existence is a critical part of robust shell scripting. You will learn how to check if files or directories exist and how to verify if scripts have the necessary execution permissions.

Let's get started!

Checking File Existence
Checking Directory Existence
Checking Script Execution Permissions

Before running a script, it's crucial to verify it has the necessary execution permissions. The -x flag helps us achieve this.

The [ -x $script ] command checks if the specified file has execution permissions. This command returns true when the path stored in the variable script exists and has execution permissions. This command returns false if the path stored in the variable script does not exist or it exists but does not have execution permissions. Consider this example:

#!/bin/bash

# Creating an executable script
touch example.sh
chmod +x example.sh

# Check if a script has execution permissions
script="example.sh"
if [ -x $script ]; then
  echo "Script '$script' has execution permissions."
else
  echo "Script '$script' does not have execution permissions."
fi

In this script:

  • touch example.sh creates an empty script named example.sh.
  • chmod +x example.sh grants execution permissions to example.sh.
  • The variable script is set to example.sh.
  • The if [ -x $script ] statement checks if example.sh exists and has execution permissions.
  • If the script is executable, echo "Script '$script' has execution permissions." prints a confirmation message.
  • Otherwise, an alternate message indicates the script lacks execution permissions.

The output of this script is:

Script 'example.sh' has execution permissions.

Using the -x operator, we can prevent execution errors by verifying that the necessary permissions are in place, thereby avoiding potential runtime issues and permission-related errors.

Summary and Next Steps

Well done! In this lesson, you learned how to:

  1. Ensure a file exists before performing operations using [ -f $file ].
  2. Verify a directory's existence with [ -d $directory ].
  3. Check for script execution permissions using [ -x $script ].

Next, you will apply these techniques in practice exercises. These exercises will solidify your understanding and help you become more confident in writing robust shell scripts.

Happy scripting, and let's move on to the practice section!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal