Lurch
Lurch

Reputation: 875

Encrypting multiple files in bash script

using the following script to encrypt files

#!/bin/bash
# crypten - a script to encrypt files using openssl

FNAME=$1

if [[ -z "$FNAME" ]]; then
echo "crypten <name of file>"
echo "  - crypten is a script to encrypt files using des3"
exit;
fi

openssl des3 -salt -in "$FNAME" -out "$FNAME.des3"

this only allow one file in and one file out, what i'd like to be able to do is batch encrypt files with a certain extension. ie if I have a folder with 1.text 2.text 3.text 4.text I want to be able to do crypten *.text and it converts all four files to .des3

Upvotes: 1

Views: 2860

Answers (2)

Nikolai Popov
Nikolai Popov

Reputation: 5675

Use the Unix philosophy - one tool for one specific task.
You want encrypt one file, it's ok - you can use your own script for it.
You want to apply script for each file in directory - xargs doing it well:

ls -1 dir_name/*.text | xargs -d '\n' -i crypten {}

Upvotes: 2

chepner
chepner

Reputation: 531135

Iterate over the positional arguments; using $# to check that at least one was received and $@ (quoted) to retrieve each one in order.

if (( $# == 0 )); then
    echo "crypten <file1> [ <file2> ... ]"
    echo "  - crypten is a script to encrypt file using des3"
    exit
fi
for FNAME in "$@"; do
    openssl des3 -salt -in "$FNAME" -out "$FNAME.des3"
done

Upvotes: 1

Related Questions