-2

I'm trying to iterate over a list of files in a directory, encrypt them, and move them somewhere else using bash. Here is what I have so far:

for filename in /home/anthony/documents_preprocessed; do 
    gpg --encrypt --recipient anthony@mydomain.org $filename
    mv /home/anthony/$filename /home/anthony/Documents
done

As I understand it, this should work but I'm fairly new to bash scripting. When I run this, it never encrypts and it just moves the file to the documents directory.

Can anyone tell me what the correct way of doing this is?

Thanks!

that other guy
  • 116,971
  • 11
  • 170
  • 194
CajunTechie
  • 605
  • 1
  • 8
  • 21
  • 2
    `for filename in dest/*`, not `for filename in dest`. `"$filename"`, not `$filename`. And GnuPG doesn't overwrite its input files by default -- which is to say that it doesn't encrypt in-place, and you probably don't want it to; too easy to have data loss in that case. Specify an output file on the gpg command line. – Charles Duffy Aug 09 '14 at 00:11
  • 1
    Also, "how do I do this in bash?" is a _horrible_ question title, as it doesn't give anyone an idea of what "this" is. Part of the goal of StackOverflow is to build a reusable knowledge base, so other folks can learn from questions and answers; questions titled "How do I do this in bash?" don't usefully contribute to that base. – Charles Duffy Aug 09 '14 at 00:13
  • if the real question is how to iterate over directory contents, then this is a dupe: http://stackoverflow.com/questions/21954516/iterate-over-files-in-directory-using-bash-script, http://stackoverflow.com/questions/20796200/how-to-iterate-over-files-in-directory-with-bash, http://stackoverflow.com/questions/1732861/linux-iterate-over-files-in-directory, etc. – Charles Duffy Aug 09 '14 at 00:41

1 Answers1

3

Use a glob to expand all files in your directory:

for filename in /home/anthony/documents_preprocessed/*; do 
    gpg --encrypt --recipient anthony@mydomain.org "$filename"
    mv "/home/anthony/$filename" /home/anthony/Documents
done

You can and should do shopt -s nullglob first, which will make the loop run 0 instead of 1 times if there are no matching files.

PS: shellcheck automatically points out common problems like this.

that other guy
  • 116,971
  • 11
  • 170
  • 194