[ale] Bash Script

Tom Wiencko tew at wiencko.com
Sun Feb 7 16:51:38 EST 1999


David S. Jackson wrote:
> 
> Hi,
> 
> Is there a way to show ONLY directories from ls?  I couldn't think of a way,
> so I wrote a little thing called "lsd".
> 
> <quote>
> 
> #!/bin/sh
> 
> #  This script lists only directories in the current directory--I
> #  don't know how to make ls do that!  So I wrote this little script.
> 
> curdir=${1:-$PWD}
> 
> echo $curdir                      #  This is for debugging
> 
> for dirname in $(ls $curdir)
>   do
>      if [ -d $dirname ]; then echo -ne "\t $dirname"
> 
>      fi
>   done
> 
> echo -e "\n"
> 
> </quote>
> 
> First, for some reason, I can't seem to get the script to act on the $1 argument.
> When I enter
> 
> lsd /home
> 
> I should get all the directories in /home.  But that doesn't happen.  What
> am I doing wrong?
> 

ls does not, but find does.  The following will do what you want:

        find -type d -maxdepth 1 -ls

If you want to specify another directory to search, 

        find /home -type d -maxdepth 1 -ls

If you don't want the long listing, remove the -ls.


Second, to fix the script, change the if statement to

	if [ -d $curdir/$dirname ]; then echo -ne "\t $dirname"

This will do the -d test in the right directory.



> Second, is there a way I can "echo" a line across the screen similar to ls
> -C?  It works the way I have it (with echo -ne) but the column doesn't wrap
> evenly onto the next line; it breaks in the middle of a word.  Any hints?
> 

This is a little more difficult, but not too bad.  Change the script
to:

#---------------------------------------------------------
#!/bin/sh

#  This script lists only directories in the current directory--I
#  don't know how to make ls do that!  So I wrote this little script.

curdir=${1:-$PWD}

echo $curdir                      #  This is for debugging
lineout=""			# initialize
maxcol=`tput cols`		# determine how wide the terminal is
for dirname in $(ls $curdir)
  do
     if [ -d $curdir/$dirname ]; then {
        lineouta="$lineout\t$dirname";  # create new output line
#if new output line is too long, send previous one, and 
#  continue to accumulate new entries.
        if [ `echo -e $lineouta |expand| wc -c ` -gt $maxcol ] ; then 
                { echo -e "$lineout"; lineouta="$dirname"; }
        fi
        lineout="$lineouta" 
        } 
     fi
  done

echo -e "$lineout\n"	# flush last entries.

#-------------------------------------------------------

There may be a more elegant way to do this, but this will work for
a quick and dirty.

Hope this helps.

-Tom
-- 
----------------------------------------------------------------------
Tom Wiencko                                            tew at wiencko.com
President - Wiencko & Associates, Inc.






More information about the Ale mailing list