Bash – Create a nickname to substitute a string without $VARIABLE, in bash cli

aliasbashvariable

Is it possible to create nicknames for frequently used strings, without using the '$' in front of $variables?

The string can be fixed and does not need to change for the lifetime of the shell prompt.

I know there are bash $variables but I am looking for a solution without using the '$' in front of a $variable, so it is quicker to type.

I know there are aliases to shorten the whole command, but I do not want to shorten a command, I want to shorten only part of a command.

For example, I want to replace this:

$ ssh remote_server_1
$ scp remote_server_1
$ my_script.sh remote_server_1

$ ssh remote_server_2
$ scp remote_server_2
$ my_script.sh remote_server_2

with this:

$ aliasthingy r1="remote_server_1"
$ aliasthingy r2="remote_server_2"

$ ssh r1
$ scp r1
$ my_script.sh r1
$ another_script.sh r1

$ ssh r2
$ scp r2
$ my_script.sh r2
$ another_script.sh r2

without doing this:

$ export r1="build_server_r1"
$ export r2="build_server_r2"

$ ssh $r1
$ scp $r1
$ my_script.sh $r1
$ another_script.sh $r1

$ ssh $r2
$ scp $r2
$ my_script.sh $r2
$ another_script.sh $r2

The reason is, it is quicker to type without '$' in front of each r1 r2 than $r1 $r2, so it would be great if I can drop the '$'

Best Answer

For the specific use case of SSH, aliases in ~/.ssh/config are the way to go. This is the way to abbreviate a host parameter and a set of options to SSH. Not only do they not require a preceding $, but they won't be used in contexts that don't call for host names accessed over SSH, and they will be used in other contexts that call for host names accessed over SSH such as SSHFS, rsync, etc.

Host r1
HostName remote_server_1
UserName vassilis

Host r2
HostName remote_server_2
UserName vp

Host r2test
HostName remote_server_2
UserName guest

For other use cases where an alias on the command line is actually called for, zsh has global aliases, defined with alias -g. Bash has no such thing.

alias -g r1=remote_server_1
ssh r1

The main problem with global aliases is that they will trigger anywhere, even where they don't make sense.

% echo r1
remote_server_1

But they won't trigger if they're part of a word, so scp r1:/some/path . won't work.

If you want something that works anywhere on the shell command line, define a variable, and type the $. If it's really hard to type on your keyboard, you could map it to a more accessible key. For example, to make M-v insert a $, put this in your .bashrc:

readline_insert () {
  READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${1}${READLINE_LINE:$READLINE_POINT:}"
  ((READLINE_POINT += ${#1}))
}
bind -x '\ev: readline_insert \$'
Related Question