2

So I'm playing around with a simple bash program, simply to learn the basics of shell and bash. The idea is a tiny password generator that saves passwords to a .txt file. Keep in mind, this is simply something to learn shell scripting - of course I understand the premise is unsafe :)

For example, I want to be able to write

./script.sh facebook generate

Which would generate a simple string and then if I confirm - save the password and site name to the .text file.

Anyways, the problem I am having is - I'm unable to retrieve the $1 and $2 parameters on the line in which I am echoing the text to the txt file (see below). I've put a comment on the line that I can't get to work. I just get blanks in the .txt file.

Can anyway help and give some guidance on accessing the parameters inside functions?

function generate() {
    PASS="9sahdoasndkasnda89zls"
    echo $PASS
}

function storeConfirm() {
    /bin/echo -n "Do you want to store this password? Y/N "
    read answer
       if [ "$answer" == "Y" ]
           then
               echo "--------" >> pwstore.txt;
               echo $1 "=" $2 >> pwstore.txt; #This line doesn't work, can't seem to access the $1 and $2 params
               echo "Successfully stored for you"
           else 
                echo "Ok... have it your way"
       fi
}

if [[ $2 == "generate" ]]; then
    generate
    echo "for site=" $1
    storeConfirm
fi
user2656127
  • 655
  • 2
  • 15
  • 30

1 Answers1

4

Since you can pass parameters to a function in the same way you can pass parameters to a script you have to make sure the script parameters get "forwarded" to the function. In other words - a function has its own "parameter scope". An example:

$ cat script
#!/usr/bin/env bash

_aFunction(){
    echo "Parameter 1: ${1}"
    echo "Parameter 2: ${2}"
}

_aFunction
_aFunction "$1" "$2"
_aFunction One Two

$ ./script 1 2
Parameter 1:
Parameter 2:
Parameter 1: 1
Parameter 2: 2
Parameter 1: One
Parameter 2: Two
Saucier
  • 4,000
  • 1
  • 23
  • 46