Search code examples
bashasciifile-type

Determine if file type is ASCII text in bash


I have to sort and print all the file names of files that are ASCII text from a given folder. I made this so far but the file names are printed even if they are PNG images.

#!/bin/bash

for f in $1/*
do
nume=$(basename $f)

if [ 'file $nume'=="$1/$nume: ASCII text" ]; then
    echo $nume
fi
done

Can someone please explain what`s wrong with my code?


Solution

    1. [ wants just an equal sign, not two, and it needs to be separated by spaces (see help test):

      [ 'file $nume' = "$1/$nume: ASCII text" ]
      
    2. You need $(...) to get the output from a command:

      [ "$(file $nume)" = "$1/$nume: ASCII text" ]
      
    3. Why are you using basename? file is not going to find your file if you don't give it the whole path:

      for f in $1/*
      do
          if [ "$(file $f)" = "$f: ASCII text" ]; then
              echo $f
          fi
      done
      
    4. Always quote your expansions. Quoting can save you a lot of headaches:

      for f in "$1"/*
      do
          if [ "$(file "$f")" = "$f: ASCII text" ]; then
              echo "$f"
          fi
      done
      
    5. (Optional) Personally, I'd take advantage of [[ and regex matching:

      if [[ "$(file "$f")" =~ ': ASCII text'$ ]]; then