BASH Shell: Test If a File Is Writable or Not

in Categories , , , , , , , , , , , , last updated December 12, 2008

Q. How can you test if a file is writable under UNIX / Linux bash shell scripting?

A. You can easily test if a file is writable or noting test command under UNIX / Linux.

The -w option

The -w option is used to test if a FILE exists and write permission is granted or not. It returns true if a file is writable.

General syntax is as follows:
[ -w filename ] && echo "Writable" || echo "Not Writable"
test -w filename && echo "Writable" || echo "Not Writable"

Here is a sample shell script:

#!/bin/bash
FILE="$1"
 
[ $# -eq 0 ] && exit 1
 
if [ -w "$FILE" ] 
then
   echo "Write permission is granted on $FILE"
else
   echo "Write permission is NOT granted on $FILE"
fi

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 3 comments/add one below):

3 comment

  1. hi,
    how to find whether the file is exist or not when the file is given from command line argument in unix os and also how to check the file permission of read and write.
    thank you.

    Have a question? Post it on our forum!