1

I'm no so advanced in bash so can not make my function work properly. Here is the code:

archive()
{
for f in $PWD
do 
    for ((i=1; i++;))
    do
        7za a "$1".7z $f -pSECRET -mhe 
    done
done
}

In order this function should take arbitrary amount of parameters like

archive foo file1.txt file2.jpg file3.asc ...

Unfortunately I've not figured out how to solve this myself.

And one more thing. For me it's still hard to make function inside function but would be perfect if someone show me how use dynamic password instead of constant one:

gpg --gen-random 1 "$1" | perl -ne'
    s/[\x00-\x20]/chr(ord($^N)+50)/ge;
    s/([\x7E-\xDB])/chr(ord($^N)-93)/ge;
    s/([\xDC-\xFF])/chr(ord($^N)-129)/ge;
    print $_, "\n"'

Ultimate desired output for command archive foo file1.txt file2.png:

7-Zip (A) [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
p7zip Version 9.20 (locale=ru_RU.UTF-8,Utf16=on,HugeFiles=on,8 CPUs)
Scanning

Creating archive .7z

Compressing  file1.txt      
Compressing  file2.png      

Everything is Ok

Password for file foo.7z is X;~2\$82uZx@^22nFd}!jrn2]`[GceWx 
1

Why are you iterating over $PWD? that is not a list.

To iterate over all arguments to a script or function, use

for ARG in "$@"; do

or the short form

for ARG;

You can use "shift" to save the first parameter to a variable, then use the loop as above to iterate over the rest of the parameters.

For the GPG part, you just need to define another function with your GPG code, then call it inside your "archive" function just as if it were a normal shell command:

gen_password () {
    gpg --gen-random 1 "$1" | perl -ne'
        s/[\x00-\x20]/chr(ord($^N)+50)/ge;
        s/([\x7E-\xDB])/chr(ord($^N)-93)/ge;
        s/([\xDC-\xFF])/chr(ord($^N)-129)/ge;
        print $_, "\n"'
}

archive () {
    ARCHIVE_NAME="$1"
    PASSWORD=$(gen_password 32)
    shift
    for ARG; do
        7za a "$ARCHIVE_NAME" "$ARG" -p"$PASSWORD" -mhe
    done
    echo "Created 7z archive with password '$PASSWORD'"
}
  • Thanks a lot for tips, hope this snippet will help someone else – im_infamous Dec 2 '15 at 22:29
  • there is no need for the 'echo' to be before shift, it can be done right after creating the archive, as anyway $PASSWORD will survive until the function returns. – AlvaroGMJ Dec 3 '15 at 0:25
  • 2
    It appears that 7z a happily accepts multiple files as operands, so the for loop is not necessary. Just use 7za a -p"$PASSWORD" -mhe -- "$ARCHIVE_NAME" "$@". This matches the desired output better because 7za is only launched once. – Arthur2e5 Dec 9 '15 at 3:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.