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
2
  • why you can not pass them as function parameters? stackoverflow.com/questions/6212219/… Commented Apr 2, 2014 at 12:43
  • I guess I could - thanks for input @alinoz Commented Apr 2, 2014 at 12:57

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Done :) Shell scripting journey continues :)
Next task @Ube is to somehow build an alias that allows parameters also:)
Have fun! :) If you are looking for good resources have a look at wiki.bash-hackers.org/ and mywiki.wooledge.org/BashGuide. These helped me a lot in the past.
Oh awesome! Exactly what I needed :) I think this can be a solid first project for me. Simple password storage and then work more with encryption and robust lookups etc :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.