Create a bash script that checks if a file is readable and writable

Here are the simple steps to create a bash script that checks if a file is readable and writable.

Create a new file as mentioned below.
vi check_permissions.sh
Copy and paste below script that checks if a file is readable and writable.
#!/bin/bash

# Check if the number of arguments is correct

if [ "$#" -ne 1 ]; then

echo "Usage: $0 <file>"

exit 1

fi

# Get the file path from the command line argument

file_path=$1

# Check if the file exists

if [ ! -e "$file_path" ]; then

echo "Error: File $file_path does not exist."

exit 2

fi

# Check if the file is readable

if [ -r "$file_path" ]; then

echo "File $file_path is readable."

else

echo "File $file_path is not readable."

fi

# Check if the file is writable

if [ -w "$file_path" ]; then

echo "File $file_path is writable."

else

echo "File $file_path is not writable."

fi

Explanation:
1. Shebang (“#!/bin/bash”):

– This line at the beginning of the script specifies the interpreter to be used (Bash, in this case).

2. Command Line Argument Check:
if [ “$#” -ne 1 ]; then:

This line initiates an if statement.

“$#” represents the number of command-line arguments passed to the script, and -ne is the “not equal” comparison operator.

So, the condition checks whether the number of command-line arguments is not equal to 1.

echo “Usage: $0 <file>”:

If the condition in the if statement is true (i.e., the number of arguments is not 1), this line is executed.

It prints a message to the standard output (console) indicating the correct usage of the script.

$0 represents the name of the script itself.

exit 1:

This line is executed if the condition in the if statement is true.

It exits the script with a status code of 1. Conventionally, a non-zero exit status indicates an error.

fi:

This marks the end of the if statement.

3. File Path Assignment:

– The script assigns the file path from the command line argument to the variable “file_path”.

4. File Existence Check:

– It checks if the file exists. If not, it prints an error message and exits with status 2.

5. Readability Check (“-r”):

– The script checks if the file is readable using the “-r” test operator. If readable, it prints a message; otherwise, it prints a different message.

6. Writability Check (“-w”):

– Similarly, the script checks if the file is writable using the “-w” test operator. If writable, it prints a message; otherwise, it prints a different message.

Save this script to a file (e.g., “check_permissions.sh”), make it executable (“chmod +x check_permissions.sh”), and then run it by providing a file as an argument (e.g., “./check_permissions.sh myfile.txt”). The script will then output whether the file is readable and writable or not.

How do you feel about this post? Drop your comments below..