Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question
    
you want to check, if it is a file or directory using script?Explain a bit more. –  Avinash Raj Mar 4 at 8:19
    
@AvinashRaj Yes. If I run ./my_script file 1 file 2 file 3, how can I check in the script if file 1, file 2, or file 3 is a file or a directory or neither? –  user234607 Mar 4 at 8:25
    
if [[ -f $1 || -d $1]] - will check the first argument of the script. –  Danatela Mar 4 at 8:27
    
@Danatela The problem is that the filenames can have one or more spaces. –  user234607 Mar 4 at 8:36
    
Then use double-quotes everywhere. Or you can escape spaces by backslash. –  Danatela Mar 4 at 8:48

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.