0

Dears, i need to test an argument to check if it's a directory, normal file or other kinds of files as i know anything that is not a directory is a file so i can make a test like

br@IBMLC0B2ZJL:/mnt/d/a343$ [ -f gg.sh ] && echo "file"
br@IBMLC0B2ZJL:/mnt/d/a343$ [ -d folder ] && echo "directory"

but i just saw a question that requires to check the file if a normal file or not, is there any ideas to test that ??

The original question : "Write a shell script that accepts a file or directory name as an argument. Have the script report if it is a regular file, a directory, or other type of file. If it is a regular file, exit with a 0 exit status. If it is a directory, exit with a 1 exit status. If it is some other type of file, exit with a 2 exit status."

1

2 Answers 2

2

There are different tests you can apply in bash.

-f file is a regular file (not a directory or device file)

-d file is a directory

-b file is a block device

-c file is a character device

-p file is a pipe

-h file is a symbolic link

-L file is a symbolic link

-S file is a socket

-t file (descriptor) is associated with a terminal device This test option may be used to check whether the stdin [ -t 0 ] or stdout [ -t 1 ] in a given script is a terminal.

But from the original question, you don't need to test these all, just the regular and directory, and everything else, maybe like this?

#!/usr/bin/env bash

file="${1:-}"
[ -f "$file" ] && exit 0
[ -d "$file" ] && exit 1
exit 2
Sign up to request clarification or add additional context in comments.

1 Comment

I think it's worth pointing out that in *nix based OSes everything is some sort of a file, and accessed thru it's path , i.e. /proc/pid/.... or /path/to/file. So when a problem asks about normal file, that is where the testing with -f help (As your answer carefully shows!). Good luck to all!
1

Something like this should do:

#!/bin/bash
if [ -z "$1" ]; then
   echo "Usage: $0 /your/test/target" && exit 123
elif [ -f "$1" ]; then
   echo "file" && exit 0
elif [ -d "$1" ]; then
   echo "directory" && exit 1
else
   echo "other type of file" && exit 2
fi

Example:

root@debian10:~[0]# touch /tmp/test.file
root@debian10:~[0]# mkdir /tmp/test.dir
root@debian10:~[0]# mknod /tmp/ttyS0 c 4 64
root@debian10:~[0]# /tmp/test.sh
Usage: /tmp/test.sh /your/test/target
root@debian10:~[0]# /tmp/test.sh /tmp/test.file 
file
root@debian10:~[0]# echo $?
0
root@debian10:~[0]# /tmp/test.sh /tmp/test.dir/
directory
root@debian10:~[1]# echo $?
1
root@debian10:~[1]# /tmp/test.sh /tmp/ttyS0 
other type of file
root@debian10:~[2]# echo $?
2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.