LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Need some help with BASH scripts (https://www.linuxquestions.org/questions/linux-newbie-8/need-some-help-with-bash-scripts-632032/)

mcdcyex 03-31-2008 07:00 PM

Need some help with BASH scripts
 
Hello forum, I'm just getting into BASH scripting and need some help.

I need to write a function that takes a directory name as an argument and writes to standard output the maximum of lengths of all filenames in that directory. If the function’s argument is not a directory name, write an error message to standard output and exit with nonzero status.

Can anyone help me out? I'm sure its easy and I'm over thinking it

chrism01 03-31-2008 08:45 PM

Sounds a little like homework, but here's a good place to start:

http://www.tldp.org/LDP/abs/html/fto.html

see also the following cmds:

ls -l
echo

mcdcyex 03-31-2008 09:40 PM

actually thats exactly what is is... and yet both the book and the instructor haven't explained it well at all.

This is what the book gives for the answer, can someone break it down in plain English so I can understand it for the future:

$ function maxfn () {
> typeset -i max thisone
> if [ ! -d "$1" -o $# = 0 ]
> then
> echo "Usage: maxfn dirname"
> return 1
> fi
>
> max=0
> for fn in $(/bin/ls $1)
> do
> thisone=${#fn}
> if [ $thisone -gt $max ]
> then
> max=$thisone
> fi
> done
> echo "Longest filename is $max characters."
> }

prad77 03-31-2008 10:13 PM

$ function maxfn () {
> typeset -i max thisone
> if [ ! -d "$1" -o $# = 0 ]
> then
> echo "Usage: maxfn dirname"
> return 1
> fi

This part checks whether enough arguments are passed. if the check fails then actual usage is echoed.

> max=0
> for fn in $(/bin/ls $1)
> do
> thisone=${#fn}
> if [ $thisone -gt $max ]
> then
> max=$thisone
> fi
> done
> echo "Longest filename is $max characters."
> }

for loop is taken which loops all the files one by one.
${#fn} - basically strings treated as array . so the total number of elements is taken up here.length of the file is got with this.
then is compared with $max. if greater then $max is swaped with the greatest one.

Gentoo

chrism01 04-01-2008 12:51 AM

Read/bookmark these:

http://www.tldp.org/LDP/abs/html/
http://tldp.org/LDP/Bash-Beginners-G...tml/index.html
http://rute.2038bug.com/index.html.gz

ansumanr 04-01-2008 01:32 AM

Shell Scripting Help!!!!
 
Quote:

Originally Posted by mcdcyex (Post 3106476)
Hello forum, I'm just getting into BASH scripting and need some help.

I need to write a function that takes a directory name as an argument and writes to standard output the maximum of lengths of all filenames in that directory. If the function’s argument is not a directory name, write an error message to standard output and exit with nonzero status.

Can anyone help me out? I'm sure its easy and I'm over thinking it

Dear Friend,

OK I understand ur problem regarding the bash shell scripting in Linux environment....one thing I wish to mention before I start that its quite simillar to Unix shell scripts.

Furthermore in this regard if you want any detail or in depth knopwledge I can help with a Tutorial of my own regarding the same.

In that case you can pass me ur mail id at ansumanr@gmail.com.

Thanks.
Best wishes.

Ansuman

Ashok_mittal 04-01-2008 06:25 AM

Quote:

Originally Posted by prad77 (Post 3106645)
$ function maxfn () {
> typeset -i max thisone
> if [ ! -d "$1" -o $# = 0 ]
> then
> echo "Usage: maxfn dirname"
> return 1
> fi

This part checks whether enough arguments are passed. if the check fails then actual usage is echoed.

> max=0
> for fn in $(/bin/ls $1)
> do
> thisone=${#fn}
> if [ $thisone -gt $max ]
> then
> max=$thisone
> fi
> done
> echo "Longest filename is $max characters."
> }

for loop is taken which loops all the files one by one.
${#fn} - basically strings treated as array . so the total number of elements is taken up here.length of the file is got with this.
then is compared with $max. if greater then $max is swaped with the greatest one.

good explanation.

pixellany 04-01-2008 06:39 AM

Quote:

Originally Posted by ansumanr (Post 3106766)
Dear Friend,

OK I understand ur problem regarding the bash shell scripting in Linux environment....one thing I wish to mention before I start that its quite simillar to Unix shell scripts.

Furthermore in this regard if you want any detail or in depth knopwledge I can help with a Tutorial of my own regarding the same.

In that case you can pass me ur mail id at ansumanr@gmail.com.

Thanks.
Best wishes.

Ansuman

This is not how to use LQ. Please post your help directly or post a link to it. This way, everyone benefits.

Ashok_mittal 04-01-2008 07:08 AM

Quote:

Originally Posted by mcdcyex (Post 3106476)
Hello forum, I'm just getting into BASH scripting and need some help.

I need to write a function that takes a directory name as an argument and writes to standard output the maximum of lengths of all filenames in that directory. If the function’s argument is not a directory name, write an error message to standard output and exit with nonzero status.

Can anyone help me out? I'm sure its easy and I'm over thinking it

let the directory name is ~/x

#!/bin/sh

ls ~/x > files.txt
wc -L files.txt



run this script it will give you maximum length of all the filenames

archtoad6 04-01-2008 07:53 AM

General note to everyone posting code: it's much easier to read if you put it in a "Code:" block -- i.e. surround it w/ [CODE][/CODE] tags (see below).

While the intermediate text file files.txt may be helpful, it is not necessary:
Code:

ls  | wc -L
works, as does:
Code:

ls -1  | wc -L

ErV 04-01-2008 08:59 AM

Quote:

Originally Posted by chrism01 (Post 3106570)
see also the following cmds:

ls -l
echo

Can be done without using "ls".
Code:

#!/bin/sh

print_max_file_len(){
    maxlen=0;
    tmpdir=`pwd`
    cd "$1"
    for i in *
    do
        len="${#i}"
        #echo "$i"
        #echo "$len"
        if [ $len -gt $maxlen ]; then
            maxlen=$len
        fi
    done
    cd "$tmpdir"
    echo "$maxlen"
}

print_max_file_len "/"

I recommend reading this:
http://www.grymoire.com/Unix/Sh.html

archtoad6 04-01-2008 09:48 AM

mcdcyex,
Consider re-doing the script in light the above. I am not sure if I would recommend showing your result to your instructor, as that may put you on his/her bad side. Nor would I recommend sharing any criticisms we/I have of the text book. ;)

The 1st & most major flaw w/ the script, as you presented it, is that it has no indentation for showing its structure. While there are various schools of programming style, I believe no professional would condone teaching no indentation style at all. Here is how I would have done it:
Code:

function maxfn () {
  typeset -i max thisone
  if [ ! -d "$1" -o $# = 0 ]
  then
      echo "Usage: maxfn dirname"
      return 1
  fi

  max=0
  for fn in $(/bin/ls $1)
  do
      thisone=${#fn}
      if [ $thisone -gt $max ]
      then
        max=$thisone
      fi
  done
  echo "Longest filename is $max characters."
}

"function" is redundant, the "()" is sufficient.

I have never had to use "typeset".

Using /bin/ls instead of plain ls could actually break the script & adds no security w/o extensive other testing. If I were being sarcastic I would label it something like "pedantic BS". Furthermore $(/bin/ls $1) isn't necessary at all -- $1/* (as in for F in $1/*) will work just as well, possibly better.

Personally, I like to start bash function names w/ a '_', that makes them instantly recognizable when called in other parts of the script.

I also abhor long variable names in short programs. They may be fine for 1,000+ line C programs, but they are unnecessary in the average Bash script. I also like the convention that Bash variable names should be all capital letters. Again, it makes them instantly recognizable.

This is a bad example because the author either does not know about wc -L, or does not want to teach it at this point in the text. If the latter is true, then a different problem should have been selected to illustrate whatever principle he/she is trying to teach.


Everyone,
In the real world wc -L is too simple & compact not to use. AFAIAC, any looping through file names counting their length is bogus; unless, of course, the teacher prefaces setting the problem w/ a statement to that effect & tells you to do it anyway for the practice. :)

And thanks for the great links.

ErV 04-01-2008 11:18 AM

Quote:

Originally Posted by archtoad6 (Post 3107192)
Everyone,
In the real world wc -L is too simple & compact not to use.

It all depends on what instructor wants to see/what the original task was.

If instructor teaches how to use scripts in general, then "ls" will do.
But if instructors teaches about more complicated things, looping constructs, conditional statements, name substitution, and the original homework was something like "implement ls using unix shell", then usage of ls won't be acceptible, since in this instructor wants to see knowledge about looping constructs, etc, not the knowledge about GNU text manipulation utilities. I personally suspect that won't like "ls" usage(I might be wrong here, though), since in several universites in my area homework of the kind "implement ls using unix shell" is quite common.

Quote:

Originally Posted by archtoad6
And thanks for the great links.

I recommend to read/learn whole unix (http://www.grymoire.com/Unix/index.html) section on grymoire, since there is a lot of very usefull information. It's a pity when people use linux for 6 months or more and don't know these things... (I'm not talking about someone in particular :))

mcdcyex 04-01-2008 11:50 AM

See thank you all! I at least understood 3/4 of what you all have said :-)

This was only the 3rd question we have tried to do in BASH scripting, I'll look at all those link you all have posted. Thanks again, Ill post what the instructor has said the correct script should be when I get it.


All times are GMT -5. The time now is 01:56 AM.