Frage

I'm a beginner with bash and I don't understand why

#! /bin/sh
if ! [ -d $1 ]; then echo This is not a directory && exit 1; fi

for file in `ls $1`; 
do 
    if [ -f `$1/$file` ]; then
        echo $file is a file
    elif [ -d $file ]; then
        echo $file is a directory
    fi
done

gives me permission denied on [ -f$1/$file]

War es hilfreich?

Lösung

It's because you have surrounded the path with backticks (``) in the "if" line. That's telling the shell to execute the file (and no doubt many of the files in the folder aren't executable - hence the error). Switch to ordinary quotes.

As an aside, using backticks to capture the output of "ls" in the "for" loop is a bad idea - it will break on filenames that contain spaces (which are perfectly legal).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top