0

I have a problem with bash script that should go through every line in ready.txt file which has stored paths to files and then do something with them like in this case rm -f

ready.txt contents:

'/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf'
'/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI4.pdf'
'/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI6.pdf'

My loop that should delete thoese files but doesn't do that.

while read -r line;
do
    rm -f $line
done < ready.txt

I tested it manually:

export line='/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf'

rm -f $line

or:

rm -f '/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf'

Both of these I tested works as intended, but loop doesn't want to.

I a newbie in bash scripts. Am I missing something?

kamil_debski
  • 131
  • 8

2 Answers2

0

Am I missing something?

Checking your scripts with http://shellcheck.net before posting here.

Assuming the input file contiains:

/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI2.pdf
/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI4.pdf
/home/kamil/TEST/FOLDER ZE SPACJAMI/PLIK ZE SPACJAMI6.pdf

Quote every variable expansion to prevent word splitting:

rm -f "$line"

Most probably rm -f $line "works" in your shell because you are using zsh, not bash, while in script you use bash or sh.

Also read -r line will remove leading and trailing spaces. Use:

while IFS= read -r line

For more information, research word splitting, when and how to use quoting in shell, how double quotes differ from single quotes. Also see https://mywiki.wooledge.org/BashFAQ/001 .

To execute a command for each line of a file, use xargs, typically:

xargs -d '\n' rm < ready.txt
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Thanks for the http://shellcheck.net tool! I newer heard of it and I already know I will be using it a lot :D – kamil_debski Mar 22 '21 at 21:51
  • I really complicated it :D I have 2 files one with ```'``` quotes and one without them. Solution you posted works for the one without ```'``` quotes so it's a lot simpler than my previous. I couldn't get it to work before because spaces were messing it up but now it works great with ```while IFS= read -r line``` – kamil_debski Mar 22 '21 at 22:01
0

It doesn't work because the filenames contain single quotes in your input file ready.txt (unless the actual filenames do contain quotes, which I doubt) as rm doesn't find such files.

You need to remove them:

while read -r line;
do
    rm -f "${line//\'}"
done < ready.txt

Also, see When to wrap quotes around a shell variable?

P.P
  • 117,907
  • 20
  • 175
  • 238