I'm attempting to create a script that loops through an entire directory of files in order to find the file with the most characters in that directory. Attached is my code sample. What am I doing wrong?   1 #!/bin/bash  2 #This program takes an array of files and sees which is the largest in a directory  3   4 files=() #create an Empty array for which files will be stored  5 longest=${files[0]} #Sets point of origin for the current largest file at 0  6   7 echo Enter Directory name:  8 read dir_name  9  10 if [ -d $dir_name ]; then #Test file to see if it's a directory 11  12         for i in $dir_name/* #For loop to discern the file with the most characters 13            do 14                 files=$dir_name 15                 if [ ${#i} -gt ${#longest} ]; then 16                         longest=$i 17                         echo $i && Character count:${#files[i]} 18                 fi 19            done 20  21 elif [ ! -d $dir_name ] 22 then 23         echo Sorry not the directory we are looking for 24         exit 0 25 fi 26  27 
Please help writing script that finds file with longest filename
shell script;scripting
I see several errors in your code:In your for loop you do not have a do at the beginning and a done at the end.If you are writing if [ ... ] then in a single line you need to put ; before the then.You don't need to store the files in an array for the purposes of your script, you can iterate directly over the files in the directoryUPDATE: I have rewritten the script to do what you wanted it to do: get the file with the longest filename of the directory and print it with its character count:#!/bin/bashlongest=0if [ $# -lt 1 ]; then # if no argument given, read the directory from input    echo -n Enter directory name:     read dir_nameelse    dir_name=$1 # this allows execute the script with the directory as argumentfiif [ -d $dir_name ]; then # process if what was given is a directory    for file in $dir_name/* ; do        if [ -f $file ]; then # do it only for files            filename=$(basename $file) # get only the filename: NOT in all UNIX            if [ ${#filename} -gt $longest ]; then                longest=${#filename} # store new longest                longest_file=$file # save the file            fi        fi    done    # we are done, print results    echo -n The file with longest filename is $longest_file    echo  with a filename $longest characters longfiTEST:given a directory test with the following regular files:a ab abc abcdthe script's output looks like:The file with longest filename is test/abcd with a filename 4 characters long