Shell script to decrypt and move files from one di

2019-03-17 08:07发布

I have a directory and in it has several files. I'm trying to decrypt those files and move them to another directory. I can't figure out how to set the output filename and move it.

So, the directory structure looks like the following:

/Applications/MAMP/bin/decryptandmove.sh
/Applications/MAMP/bin/passtext.txt
/Applications/MAMP/bin/encrypted/test1.txt.pgp
/Applications/MAMP/bin/encrypted/test2.txt.pgp
/Applications/MAMP/htdocs/www/decrypted/

For all the files that are found in the encrypted directory, I'm trying to decrypt them and then move them to the directory www/decrypted/. I don't know what the filenames in the encrypted directory will be ahead of time (this script will eventually run via cron job), so I wanted to just output the decrypted files with the same filenames, but without the pgp. So, the result would be:

/Applications/MAMP/bin/decryptandmove.sh
/Applications/MAMP/bin/passtext.txt
/Applications/MAMP/bin/encrypted/
/Applications/MAMP/htdocs/decrypted/test1.txt.pgp
/Applications/MAMP/htdocs/decrypted/test2.txt.pgp

So, this is all I have written so far and it doesn't work. FILE and FILENAME are both wrong. I haven't even gotten to the moving part.

pass_phrase=`cat passtext.txt|awk '{print $1}'`

for FILE in '/Applications/MAMP/bin/encrypted/';
 do
    FILENAME=$(basename $FILE .pgp) 
    gpg --passphrase $pass_phrase --output $FILENAME --decrypt $FILE
 done

3条回答
神经病院院长
2楼-- · 2019-03-17 08:20

This should fix the FILENAME and FILE problems, although it will only work if you're in the "decrypted" directory right now. If you want to fix that you'll have to add the correct directory to the FILENAME variable :)

pass_phrase=`cat passtext.txt|awk '{print $1}'`

for FILE in /Applications/MAMP/bin/encrypted/*; do
    FILENAME=$(basename $FILE .pgp) 
    gpg --passphrase $pass_phrase --output $FILENAME --decrypt $FILE
done
查看更多
小情绪 Triste *
3楼-- · 2019-03-17 08:30

I like to do a cd first:

cd /Applications/MAMP/bin/encrypted/

Then

for FILE in $(ls); do ...

or

for FILE in `ls`; do ...

I personally prefer:

ls | while read FILE; do ...

Then maybe

cd -

Important: If you use the ls approach, make sure that your filenames don't contain spaces. See also the link in ghostdog74's comment (thanks, BTW) - this page is generally quite useful.

查看更多
放我归山
4楼-- · 2019-03-17 08:34
#!/bin/bash
p=$(<passtext.txt)
set -- $p
pass_phrase=$1
destination="/Applications/MAMP/htdocs/www/decrypted/"
cd /Applications/MAMP/bin/encrypted
for FILE in *.pgp;
do
    FILENAME=${FILE%.pgp}
    gpg --passphrase "$pass_phrase" --output "$destination/$FILENAME" --decrypt "$FILE"
done
查看更多
登录 后发表回答