Talk:TIP lowercase files and directories

From Gentoo Linux Wiki

Jump to: navigation, search

Bug: reversed test
The filename in the tests should be quoted, to allow for spaces. Also, it doesn't affect the output, but I think this is a typo:

Code: original

<pre><nowiki> if [ -f $x -a -d $x ]; then

    #code never gets here... can't be -f and -d at the same time!
    continue 

</nowiki></pre>

It should be the opposite way:

Code: reversed test

<pre><nowiki> if [ ! ( -f "$x" || -d "$x" ) ]; then

   #code gets here for pipes etc
    continue

</nowiki></pre>

Also, since you are essentially using the same code in the loop, the whole thing could be written as:

File: lowerit.sh

<pre><nowiki>

  1. !/bin/sh
  2. January 22, 1998
  3. Some ideas borrowed from the Tips-HOWTO. Modifications by BJ Goodwin
  4. <latency@radiolink.net>.
  5. Copyleft 1998
  6. All Beers Consumed.

if [ ! $1 ]; then

       echo "Not enough arguments. Try $0 -h for options."
       exit 1

fi

case "$1" in

   "-f"| "-d" ) test="[[ $1 \"\$x\" ]]" ;;
   "-a" ) test='[[  ( -f "$x" || -d "$x" ) ]] ;;
   "-h" )
           echo "-----------------------------------------------------------"
           echo "lowercase v1.0 - Convert files or directories to lowercase."
           echo "-----------------------------------------------------------"
           echo "Usage: $0 <option>"
           echo
           echo "Options:"
           echo " -f = All files in current directory."
           echo " -d = All directories in current directory."
           echo " -a = All files AND directories in current directory."
           echo " -h = This help screen."
           echo
           echo "Notes: If a lowercase directory already exists that has the same"
           echo " name as the uppercase directory, the uppercase will be"
           echo " MOVED to the lowercase directory without confirmation."
           exit
           ;;
   * )
           echo "$0: Invalid argument. Try $0 -h for help."
           exit 1;;

esac

  1. "for x in *" properly handles filenames with spaces
  2. unlike constructs like: for x in `ls`

for x in *

   do
   if   eval "$test"   ; then
       convert=`echo $x | tr '[A-Z]' '[a-z]'`
       if [ "$convert" != "$x" ]; then
            mv -i "$x" "$convert"
       fi
   else
       continue
   fi

done </nowiki></pre>

Don't know if that's any easier to understand, but it's shorter :-)
Ajasen 05:08, 25 December 2005 (GMT)
Personal tools