Test writability with test -w
In this step, we will learn how to check if you have permission to write to a file or directory using the test
command with the -w
option. Understanding file permissions is crucial in Linux, as it determines who can read, write, and execute files.
The test
command is a built-in shell command that checks for conditions and returns an exit status of 0 (true) or 1 (false). The -w
option specifically checks if a file or directory is writable by the current user.
Let's create a simple file in your ~/project
directory. We'll use the touch
command, which creates an empty file if it doesn't exist.
Navigate to your project directory if you are not already there:
cd ~/project
Now, create a file named my_test_file.txt
:
touch my_test_file.txt
You can verify the file was created using the ls
command:
ls
You should see my_test_file.txt
listed in the output.
Now, let's use the test -w
command to check if you can write to this file. We'll combine it with an echo
command to see the result.
test -w my_test_file.txt && echo "Writable" || echo "Not writable"
Let's break down this command:
test -w my_test_file.txt
: This checks if my_test_file.txt
is writable.
&& echo "Writable"
: If the test
command returns true (exit status 0), the &&
operator executes the next command, which prints "Writable".
|| echo "Not writable"
: If the test
command returns false (exit status 1), the ||
operator executes the next command, which prints "Not writable".
Since you created the file as the labex
user in your home directory, you should have write permissions, and the output should be:
Writable
The test -w
command is often used in shell scripts to check permissions before attempting to write to a file, preventing potential errors.
Click Continue to proceed to the next step.