I am working with a pretty simple bash script, but I am facing a problem which I can't resolve:
I have myscript.sh
with three parameters, -u
, -h
, and -p
.
Both -u
and -h
are mandatory, needed for the script to run.
What I would like to do is, if myscript.sh -u User1
and nothing more it should terminate with exit 1
.
I want my script to analyze and just run the script if myscript.sh -u User1 -h Localhost
are on the options, otherwise it should exit.
Many thanks
Best Answer
Maybe something like this?
The main bit here is the short
if
statement at the end that tests whether there were ever anything assigned to thehost
oruser
variables in thewhile
loop. If either of these variables are empty, then the code treats it as an error and exits after outputting a short diagnostic message.The script shown above should also be able to run under
/bin/sh
as it does not contain any bashishms.Instead of the
if
statement, you could useor, even shorter,
The
:
command is a utility that doesn't do anything, but its argument would still be processed by the calling shell, like for all commands. With the two lines above, the shell would try to expand thehost
anduser
variables, and if the variable is unset, or if the expansion results in an empty string, then the string to the right after?
will be outputted and the script will terminate with a non-zero exit status:The
${variable:?text}
expansion is standard and therefore supported bybash
and all other POSIXsh
-like shells.