Ubuntu – How to check in a bash script if passed argument is file or directory

bashscripts

I have to write a simple bash script in Ubuntu which would allow me to pass it some arguments and I want to check if these arguments which can contain spaces are files or directories. How can I do this?

Best Answer

Example script:

#!/bin/bash
# This is a simple demo script
# It takes 3 parameters and checks if they are files or directories

echo "Welcome to my script"

if [[ -f "$1" || -d "$1" ]]
then
    echo "The First argument is a file or directory"
fi

if [[ -f "$2" || -d "$2" ]]
then
    echo "The second argument is a file or directory"
fi

if [[ -f "$3" || -d "$3" ]]
then
    echo "The third argument is a file or directory"
fi

echo "Bye!"

Example scenario

I saved script as ~/script.sh and did chmod +x script.sh

karimov-danil@Karimov-Danil:~$ ./script.sh "Шаб лоны" "Обще доступные" "ta lk" 
Welcome to my script
The First argument is a file or directory
The second argument is a file or directory
The third argument is a file or directory
Bye!

Note: you should pass arguments inside double-quotes.