Akshay Kumar
Akshay Kumar

Reputation: 11

Use two config variables in bash script

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?

Upvotes: 0

Views: 193

Answers (2)

narendra
narendra

Reputation: 1278

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

Upvotes: 1

buratino
buratino

Reputation: 1518

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.

Upvotes: 1

Related Questions