Shell programming, lopping thorugh files

I am trying to loop through files in a specified directory. But I can't seem to figure out the logic. Can someone help? 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 loop
############################  
else
echo 'not a file'
  fi#1st if loop
#######################################

done

Answers


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.


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/*

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

Need Your Help

Activating the main form of a single instance application

c# .net winforms

In a C# Windows Forms application I want to detect if another instance of the application is already running.

Host is null in NsdServiceInfo of NsdManager.DiscoveryListener.onServiceFound

android networking listener discovery

I'm trying to get the mHost of the NsdServiceInfo passed as parameter to NsdManager.DiscoveryListener.onServiceFound() but it's null.