Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an argument is a path

Tags:

bash

I'm writing a script in bash. It will receive from 2 to 5 arguments. For example:

./foo.sh -n -v SomeString Type Directory

-n, -v and Directory are optional. If script doesn't receive argument Directory it will search in current directory for a string. Otherwise it will follow received path and search there. If this directory doesn't exist it will send a message.

The question is: Is there a way to check if the last arg is a path or not?

like image 833
user1872329 Avatar asked Apr 26 '14 11:04

user1872329


People also ask

How do I know if an argument is a directory?

First check the provides argument is the directory or not using the if statement using the -d option for the first argument using the $1 parameter. If it is true then print the message that the provided argument is the directory. If the argument is not the directory then check it for the file.

How do you check if an argument is a directory bash?

In order to check if a directory exists in Bash, you have to use the “-d” option and specify the directory name to be checked.

How do you check if a file is a directory in shell script?

Checking If a Directory Exists In a Bash Shell Script -h "/path/to/dir" ] && echo "Directory /path/to/dir exists." || echo "Error: Directory /path/to/dir exists but point to $(readlink -f /path/to/dir)." The cmd2 is executed if, and only if, cmd1 returns a non-zero exit status.


1 Answers

You can get last argument using variable reference:

numArgs=$#
lastArg="${!numArgs}"

# check if last argument is directory

if [[ -d "$lastArg" ]]; then
   echo "it is a directory"
else
   echo "it is not a directory"
fi
like image 133
anubhava Avatar answered Sep 19 '22 16:09

anubhava