Test executability with test -x
In this step, you will learn how to check if a file is executable using the test
command with the -x
option. The test
command is a built-in shell command that evaluates conditional expressions. The -x
option specifically checks for the executable permission.
First, let's create a simple text file in your ~/project
directory. We'll use the echo
command to put some text into a file named my_script.sh
.
echo "echo 'Hello from the script!'" > ~/project/my_script.sh
Now, let's check if this file is executable. By default, when you create a new file this way, it won't have execute permissions.
Use the test -x
command followed by the path to the file:
test -x ~/project/my_script.sh
After running this command, you won't see any output if the test is successful (meaning the file is NOT executable). If the file were executable, test -x
would return a status of 0, which is typically interpreted as "true" or "success" in shell scripting, but it doesn't print anything to the terminal by default.
To see the result of the test
command, we can check the exit status of the previous command using $?
. An exit status of 0
means the test was true (the file is executable), and a non-zero status (usually 1
) means the test was false (the file is not executable).
echo $?
You should see an output of 1
, indicating that my_script.sh
is currently not executable.
Now, let's make the file executable using the chmod
command. chmod
is used to change the permissions of files and directories. We'll use +x
to add the execute permission for the owner of the file.
chmod +x ~/project/my_script.sh
Now, let's test for executability again:
test -x ~/project/my_script.sh
And check the exit status:
echo $?
This time, the output should be 0
, confirming that the file is now executable.
Finally, let's try running the script to see the output:
~/project/my_script.sh
You should see:
Hello from the script!
This confirms that you successfully made the file executable and ran it.