Search code examples
bashunixpwd

shell script: bad interpreter: No such file or directory when using pwd


I want to go through the files in a directory with a for loop but this comes up.

echo: bad interpreter: No such file or directory

code:

#!/bin/bash
count=0
dir=`pwd`
echo "$dir"
FILES=`ls $dir`
for file in $FILES
do
 if [ -f $file ]
 then
  count=$(($count + 1))
 fi
done
echo $count

Solution

  • Better do :

    #!/bin/bash
    count=0
    dir="$PWD"
    echo "$dir"
    
    for file in "$dir"/*
    do
     if [[ -f $file ]]
     then
      ((count++))
     fi
    done
    echo $count
    

    or a simplest/shortest solution :

    #!/bin/bash
    
    echo "$PWD"
    
    for file; do
     [[ -f $file ]] && ((count++))
    done
    
    echo $count