Test command line argument to check for directory, file and permission on bash

bash
linux
test

#1

Write a shell script to test whether a given

  1. file is directory or not
  2. file has read permission or not
  3. file has write permission or not
  4. file has execute permission or not

Assume file name is given as command line argument.


#2

You need to use test or [ … ] syntax.

Find out if a file is a directory or not

[ -d "$f" ] && echo "directory: yes" || echo "directory: no"

Find out if a file is a regular file or not

[ -f "$f" ] && echo "file: yes" || echo "file: no"

Find out if a file has a read permission or not

[ -r "$f" ] && echo "read permission: yes" || echo "read permission: no"

Find out if a file has a write permission or not

[ -w "$f" ] && echo "write permission: yes" || echo "write permission: no"

Find out if a file has an execute permission or not

[ -x "$f" ] && echo "execute permission: yes" || echo "execute permission: no"

Shell script to test various file attributes

#!/bin/bash
f="$1"

[ "$f" == "" ] && { echo "$0 file"; exit 1; }

echo
echo "File \"$f\" has the following permission for user \"$USER\":"
echo
[ -d "$f" ] && echo "directory: yes" || echo "directory: no"
[ -f "$f" ] && echo "file: yes" || echo "file: no"
[ -r "$f" ] && echo "read permission: yes" || echo "read permission: no"
[ -w "$f" ] && echo "write permission: yes" || echo "write permission: no"
[ -x "$f" ] && echo "execute permission: yes" || echo "execute permission: no"


#3

I prefer test which is more explicit than [.


#4

yes, test and [ and [[.