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?
1 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.
./my_script file 1 file 2 file 3
, how can I check in the script iffile 1
,file 2
, orfile 3
is a file or a directory or neither?if [[ -f $1 || -d $1]]
- will check the first argument of the script.