开发者

Shell programming, looping through files

I am trying to loop through files in a specified directory. But I can't seem to figure out the logic. I am looping through each file and asking if they want to delete that file.

#!/bin/bash
dirpath=$1
y=y
Y=Y
echo "changing directory '$dirpath' `cd $dirpath`"

for f in $1/*
do
#####################################
if test -f `ls -1 $1`
then
echo -n "remove file '$f' `ls -1` ?"
read answer
##########################
if test $answer = $y || test $answer = $Y
then

  echo "Processing $f file..."
  echo `rm $f`
    echo "file '$f' deleted "
else
echo "file '$f' not removed"

  fi#2nd if l开发者_如何学JAVAoop
############################  
else
echo 'not a file'
  fi#1st if loop
#######################################

done


Your code seems much more complicated that it should be. Does this fulfill your needs or are you doing some shell practice?

rm -iv DIRECTORY/*


There's no need for ls, you already have the filename. Change this:

if test -f `ls -1 $1`

to:

if test -f "$f"

Why are you using echo and backticks here? Change

echo `rm $f`

to:

rm "$f"

Here's another place you're using backticks unnecessarily. Change this:

echo "changing directory '$dirpath' `cd $dirpath`"

to:

echo "changing directory '$dirpath'"
cd "$dirpath"

Always quote variables that contain filenames.


You can have rm do the "asking" for you via its -i flag to prompt user before removal. I am assuming you want to consider only files, not directories, and not recurse any sub-directories.

#!/bin/bash

for f in $1/* ; do 
    if [ -f $f ] ; then 
        rm -i $f ; 
    fi
done


Without the error, can't really help, but it could be written like this, not as verbose though

rm -i *


If $1 is a relative path, then once you've cd'd into $1, the wildcard in your for loop will be meaningless. I'd recommend something more like

 cd $1
 for f in *; do
    ...
 done

Since it will accept both relative and absolute paths.

Moreover, the arguments to the first test are wrong. Each time through the loop, $f will hold one filename, so your test should be like

 if (test -f $f); then

You also repeat this in your echo arguments.

The following does basically what you want, with only slight modifications from your script.

#!/bin/bash
dirpath=$1
y=y
Y=Y
echo "changing directory '$dirpath' `cd $dirpath`"

for f in ./*; do

if (test -f $f); then
        echo -n "remove file '$f' ?"
        read answer
        if (test $answer == $y) || (test $answer == $Y); then

                echo "Processing $f file..."
                rm $f
                echo "file '$f' deleted "
        else
                echo "file '$f' not removed"
        fi
else
        echo 'not a file'
fi

done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜