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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With