Make a table listing the file name, number of lines and whether its a director or file

Viewed 44

So ive coded before but not too in depth. We have been working on assignments which I have figured out but this is my first using BASH to write scripts in Linux. my professor gave us this code:

#!/bin/sh
cd /tmp
var=`/bin/ls`
for a in $var
do
        if [ -f $a ]
        then
          /bin/ls -l $a
        else
          /bin/ls -ld $a
        fi
done

but i am still confused on what it even means.... any help?

1 Answers
#!/bin/sh         # so-called hashbang/shebang defines which binary will be used to execute following code
cd /tmp           # change directory to /tmp
var=`/bin/ls`     # execute `ls` command, and store its output into `var`
for a in $var     # at first glance its just header of iteration statement
                  # but there are few tricks hidden in it, for example 
                  # fragile characters: if you have multi-word filename
                  # each word will be treated separately
                  # so if you have file "/tmp/log september"
                  # the loop will try to iterate with "log" and with "septemper"
                  # which ofc might (and usually does) lead to issues... just telling so you are aware 
do
        if [ -f $a ]  # if iterated element is REGULAR file (there are several types of files)
        then
          /bin/ls -l $a  # just ls (with columns format) the file, 
        else             # if it does not exist or exist but its not regular file
          /bin/ls -ld $a # try to ls it treating it as it was directory
                         # what actually in most cases makes sense
                         # but still... it might be socket, block device or just symlink
        fi
done

Hope that's clear enough my friend...

Related