0

I'm trying to 7zip and move some files that look like this:

./[1998] - This year's book.pdf ##note the brackets, spaces, and apostrophes

My script looks like this:

for file in `ls ./unprocessed/*.pdf`; 
do 
    7z a -mx=0 -pMyPassword $file.7z $file ;
    mv $file ./processed 
done

(This is actually on Synology's linux, if it makes a difference.)

I've tried adding quotation marks around "$file", but that doesn't help on either of the two main lines.

I'm hoping I can do this without a lot of complicated grep or sed type stuff.

The main error I'm getting is that it's trying to split out the file names due to the spaces, and freaks out because it can't find "[1998]", etc.

I think 7z will be okay with it, once I work out the spaces/funky chars issue(?).

Has anyone else run into this?

Appreciate any advice!

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Mark
  • 31
  • 1
  • 4
    See [Why doesn't my loop over the output of ls work?](http://unix.stackexchange.com/questions/128788/why-doesnt-my-loop-over-the-output-of-ls-work?) – steeldriver Jul 04 '16 at 21:53
  • 4
    Before asking a human for help with a shell script, paste it into [shellcheck.net](http://www.shellcheck.net/). – John1024 Jul 04 '16 at 22:08
  • @John2024, why are people on stackexchange always so snippy? All you had to do was mention to try shellcheck.net first, and that would have been more cheery! Cheers. – Mark Jul 04 '16 at 22:51
  • @Mark Apologies if you thought that. It was not meant to be "snippy." It was simply meant to be _concise_. Programmers tend to abhor unnecessary words. – John1024 Jul 04 '16 at 23:30

1 Answers1

1

Thanks to the tip to visit shellcheck.net, which I wasn't familiar with, the key problem was this line:

`ls ./unprocessed/*.pdf`

This is better:

for file in ./unprocessed/*.pdf

Then, adding the quotation marks around "$file" worked.

Stephen Harris
  • 42,369
  • 5
  • 94
  • 123
Mark
  • 31
  • 1
  • 3
    Be aware of the edge case where if no file matches then you'll get the literal string `./unprocessed/*.pdf` instead of a filename. In `bash` the command `shopt -s nullglob` will help. – Stephen Harris Jul 04 '16 at 23:03