0

I am trying to create a shell script that will keep the last n files in a directory and delete the rest. The config file that I am using is as under:

#config
dir1="/home/user/test"
n1="2"
dir2="/home/user/test/temp"
n2="3"

What I intend to achieve is goto dir1 and keep the last n1 files. I am testing out the following code

source /home/cfolder/config
ls -t $dir1 | sed -e '1,'$n1'd' | xargs -d '\n' rm

How do I get the code to loop through all the config parameters without explicitly writing a line of code for each dir and n group?

2 Answers 2

1

I do not know exactly how to do what you want with the way your problem is set up. However, here is another approach you can use to this kind of problem.

For separate configurations, I like to have config files named X, Y, or Z.conf (of course, replace X, Y, and Z with meaningful names).

In these .conf files, use dir and n instead of dir1 and n1.

#X.conf
dir="/home/user/test"
n="2"

and

#Y.conf
dir="/home/user/test/temp"
n="3"

Then, in a bash script, I will do:

# runconfigs.sh
for config in ./*.conf; do
    <your_script_name_goes_here>.sh "$config"
done

In your script, you can use something like

#yourscript.sh
source "$1"
ls -t $dir | sed -e '1,'$n'd' | xargs -d '\n' rm

Then, you can simply run ./runconfigs.sh. I find that this approach becomes more useful when you're dealing with many configurations, but I don't see why it isn't also applicable here.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't use ls. Just iterate over the pattern directly: for config in ./*.conf.
1

For better design perspective, suggestion is to have config file like below where first field per line is directory and second the no of files and then loop it

# config.conf
/home/user/test:5
/home/user/temp:2

# script.sh
# 
while IFS=: read -r dir days; do
    # your cmd to remove file using $dir and $days
    cd $dir
    ls -tr | head -n -$days | xargs rm
done < config.conf

2 Comments

See the Bash FAQ #1 for the correct way to iterate over the contents of a file. In conjunction with that, use read to split the line into two fields rather than calling cut twice.
Thanks @chepner modified answer to use the while loop instead of for loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.