Languages
[Edit]
EN

Bash - check if file is writable

0 points
Created by:
Maryamcc
541

In this article, we would like to show you how to check if file is writable in Bash.

Practical example

In this example, we use -w operator with specified path to check if file under the path is writable inside if statement.

script.sh file:

#!/bin/bash

path="/path/to/file.txt"

if [ -w "$path" ]; then
    echo "The file is writable."
fi

Note: this approach should be used in POSIX shells where other solutions may not work.

Run in command line:

./script.sh

Output:

The file is writable.

 

Altermative notation

1. test based solution

#!/bin/bash

path="/path/to/file.txt"

if test -w "$path"; then
    echo "The file is writable."
fi

Note: [ ] notation is shorthand of test command.

2. [[ ]] based solution

#!/bin/bash

path="/path/to/file.txt"

if [[ -w "$path" ]]; then
    echo "The file is writable."
fi

Note: [[ ]] notation is like extended test command, adding additional features (e.g. regular expressions).

 

See also

  1. Bash - check if file is executable

  2. Bash - check if file is readable

  3. Bash - check if file is socket

  4. Bash - check if file is not zero size

Alternative titles

  1. Bash - test if file is writable
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join