问题
So I basically am trying to overwrite my ssh command so I only have to type ssh and by default it would connect to my main server. Then if I passed it an argument, say username@server_port it would then run the basic command.
# Fast SSH (a working progress) TODO: make work without naming the function `fssh`
function fssh() {
ALEX_SERVER_CONNECTION=$ALEX_SERVER_UNAME@$ALEX_SERVER_PORT
# if the `ssh` argument is not set
if [ -z "${1+xxx}" ]; then
# echo "ALEX_SERVER_CONNECTION is not set at all";
ssh $ALEX_SERVER_CONNECTION
fi
# if the `ssh` argument is set
if [ -z "$1" ] && [ "${1+xxx}" = "xxx" ]; then
ssh $1
fi
}
How do I get it to work without the f in front of the ssh?
So basically this is how it looks when properly done:
# Fast SSH
function ssh() {
ALEX_SERVER_CONNECTION=$ALEX_SERVER_UNAME@$ALEX_SERVER_PORT
# if the `ssh` argument is not set
if [ -z "${1+xxx}" ]; then # ssh to the default server
command ssh $ALEX_SERVER_CONNECTION
fi
# if the `ssh` argument is set
if [ -z "$1" ] && [ "${1+xxx}" = "xxx" ]; then # ssh using a different server
command ssh $1
fi
}
回答1:
Solution
You need to specify the absolute path to ssh command in your function otherwise it will be recursive. For instance, instead of:
function ssh() { ssh $USER@localhost; } # WRONG!
You should write:
function ssh() { command ssh $USER@localhost; }
Use command built-in to get the ssh from the PATH (as suggested by @chepner):
command [-pVv] command [arg ...]
Run command with args suppressing the normal shell function lookup. **Only builtin commands or commands found in the PATH are executed**.
Why not Alias?
Using a function is the correct pattern, read the Aliases and Functions sections from the man page.
ALIASES
There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (see FUNCTIONS below).
Diagnostic
When naming your custom function ssh do the following:
- be sure to reload your shell configuration:
source ~/.bashrc - check what is
sshwith:which sshortype ssh
type and which
Prior to declaring a custom function I got:
type ssh # → ssh is /usr/bin/ssh
which ssh # → /usr/bin/ssh
After declaring function ssh() { ssh my-vm; }, I got:
which ssh # → ssh () { ssh my-vm; }
type ssh # → ssh is a shell function
Advices
Either use sh or bash syntax:
sh: test is done with[ … ], portable but not powerful ;bashtest is done[[ … ]]andfunctionkeyword, less portable but dev-friendly.
回答2:
How do I get it to work without the f in front of the ssh?
Set an alias in ~/.bashrc:
alias ssh='fssh'
回答3:
Say your script is called fssh and is executable, you just have to:
alias ssh='fssh'
in your .bashrc
来源:https://stackoverflow.com/questions/25399079/how-to-overwrite-a-bash-command