I have the following bash script:
export USER_AT_HOST="<user@ipaddress>"
export PUBKEYPATH="$HOME/.ssh/<pubkeyfilename>"
ssh-copy-id -i "$PUBKEYPATH" "$USER_AT_HOST" -p 8524
I would like to modify the script, so that <pubkeyfilename>
(which is currently hardcoded in the script), becomes a named input argument, and the same for the port number. Ideally, the script should do the following
- take two named arguments,
-p/--port
and--pubkeyfile
, respectively an integer and a path - perform input validation, i.e., check that
-p/--port
is an integer, if not empty, and that--pubkeyfile
is a string. Of course, if this is not possible or too complex in bash, you can ignore this request. - if an argument is not passed, use a default value
- if a wrong argument or the argument
-h/--help
is passed, an help message is displayed
This answer is highly regarded:
https://stackoverflow.com/a/14203146
but it doesn't show how to use default values if an argument is not passed, it doesn't perform input validation and it doesn't include an help method. Also, for the getopts
option (which wouldn't allow me to use long option names), it refers to this tutorial
https://wiki.bash-hackers.org/howto/getopts_tutorial
which however gives me the error
This site can’t provide a secure connection
wiki.bash-hackers.org sent an invalid response.
ERR_SSL_PROTOCOL_ERROR
EDIT: this question is not a duplicate of How can I use long options with the Bash getopts builtin?, because the answers there either don't show how to use getops for long options (see https://stackoverflow.com/a/12026302/1711271) or don't show how to pass long options which require an argument (https://stackoverflow.com/a/30026641/1711271), or don't show how to set a default value for an option which is not passed (all of them). My OS is MacOS.
EDIT 2: my shell is bash:
> ps -p $$
PID TTY TIME CMD
67809 ttys001 0:00.01 -bash
I'm not going to learn another shell just for the sake of a simple script. However, if I understand correctly, it's possible to write a shell script that runs another shell and then terminate. Thus a solution based on zsh
, while not ideal, could be acceptable.