Shell : Script that takes a file name as an argument and checks if it’s readable or not.

One common task is checking if a file is readable before proceeding with a script. This is useful to prevent errors when attempting to read a file that is not readable.

To check if a file is readable in a shell script, we can use the test command with the -r option. The test command is used to evaluate a condition and returns a status code of 0 if the condition is true, and 1 if it is false. The -r option checks if the file is readable and returns true if it is.

Here’s an example script that takes a file name as an argument and checks if it’s readable or not:

#!/bin/bash
if test -r "$1"; then
  echo "The file is readable."
else
  echo "The file is not readable."
fi

Let’s break down how this script works.

The first line #!/bin/bash is called a shebang and specifies which shell should be used to execute the script. In this case, we are using the bash shell.

The if statement checks if the condition inside the parentheses is true. In this case, we are using the test command with the -r option to check if the file given as an argument is readable. If it is, the test command returns true, and the if statement executes the code inside the then block.

If the file is readable, the script outputs the message “The file is readable.” using the echo command. Otherwise, if the test command returns false, the if statement executes the code inside the else block, and the script outputs the message “The file is not readable.” using the echo command.

We can run the script by saving it as a file, for example readable-check.sh, and then making it executable using the chmod command:

chmod +x readable-check.sh

We can then execute the script by passing a file name as an argument, for example:

./readable-check.sh example.txt

This will output the message “The file is readable.” if the file example.txt is readable, or “The file is not readable.” if it is not.

Checking if a file is readable is a common task in shell scripting. We can use the test command with the -r option to check if a file is readable, and the if statement to execute code based on the result of the check.

Other urls to refer

  1. PySpark Blogs
Author: user

Leave a Reply