Bash not removing all .tar.bz2 files after extracting

In the bash below each .tar.bz2 (usually 2) are extracted and then the original .tar.bz2 is removed. However, only one (presumably the first extracted) is being removed, however both are extracted. I am not sure why this is? Thank you :).

tar.bz2 folders in /home/cmccabe/Desktop/NGS/API

R_2017_02_17_13_02_53_user_S5-00580-30-Medexome.tar.bz2
R_2017_02_17_15_41_37_user_S5-00580-31-Medexome.tar.bz2
# untar and remove .tar.bz2 in API
for i in /home/cmccabe/Desktop/NGS/API/*.tar.bz2; do 
    tar -xvjf "$i" -C /home/cmccabe/Desktop/NGS/API
done
rm $i

currently in directory after code is executed:

R_2017_02_17_13_02_53_user_S5-00580-30-Medexome.tar.bz2
R_2017_02_17_13_02_53_user_S5-00580-30-Medexome
R_2017_02_17_15_41_37_user_S5-00580-31-Medexome

desired in directory after code is executed

R_2017_02_17_13_02_53_user_S5-00580-30-Medexome
R_2017_02_17_15_41_37_user_S5-00580-31-Medexome

As the "rm $i" is outside the loop, it's only executed once.

1 Like

Thank you, I thought that it needed to be outside the loop to ensure both the folders were extracted then removed. More to learn :).

That's what a loop does. The code inside it is executed several times. The code outside it is not.