0

I have a bash script that I want invoked using a require -p argument that is of type string/alphanumeric. For example:

sh myscript.sh -p abc123

My best attempt thus far:

#!/usr/bin/bash
mypassword=${p:}
echo $mypassword
if [ -z mypassword ]
then
  echo "error"
fi

Since this is a required argument, I don't have a good meaningful default to apply (hence my attempt with using ${p:} to set mypassword to empty/null, and then attempt the null check conditional right afterwards).

When I run it via sh myscript.sh -p abc123 I get:

myscript.sh: line 46: ${p:}: bad substitution

All I'm trying to accomplish is this:

If -p wasn't specified, or if it was specified, but no value for it was given (e.g. -p abc123), I want to echo "error". In other words, -p must not only be provided, but a value for it must be supplied as well.

Any ideas as to how I could accomplish this?

1

1 Answer 1

1

[ -z mypassword ] will always evaluate to false, because the word mypassword has a length greater than zero. You could test with, for instance, [[ -z $mypassword ]].

Also, the term ${p:} does not make sense. Perhaps you meant ${p:=} ?

UPDATE:

One more note: The way you are invoking your script would not work, even after those fixed, becaues mypassword will always be empty. For your script to work, p must be an environment variable holding the password. You would have to call your script (assuming it is in your working directory) like this:

# To run it as sh-script (POSIX shell)
p=THIS_IS_MY_PASSWORD sh myscript.sh 

# To run it as bash-script, if the script is executable
p=THIS_IS_MY_PASSWORD ./myscript.sh

# To run it as bash-script, if the script is not executable
p=THIS_IS_MY_PASSWORD bash myscript.sh 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @user1934428 (+1), just curious, why nest -z $mypassword inside two sets of braces ("[[" and "]]"), instead of just one set?
[[ is a syntactic construct, while [ is a command, even though bash implements it as an internal command. Íf you are only doing a -z and nothing else, [[ saves you from quoting the parameter expansion, while with [ you would have to write [ -z "$mypassword" ] to catch the case where mypassword contains a space.
Thanks again @user1934428 (+1), any chance you could give me a working code example that would allow me to invoke my script using the provided (desired) method? Such as sh ./myscript.sh -p 12345?
Gordon Davisson already did this in his comment, which also points to useful examples. I suggest that you try to follow his advice, and if you really get stuck, ask a new question and post your approach to use getopts.

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.