Skip to content
Advertisement

Backslash inside an alias not being stored as part of its definition

I’ve got a screen sessions named BedrockServer. I’ve entered the alias like this:

alias stop='screen -R BedrockServer -X stuff "stop $(printf 'r')"'

But when I type alias, it lists it as

alias stop='screen -R BedrockServer -X stuff "stop $(printf r)"'

and the alias doesn’t work.


I’ve tried messing around with the quotes and using backslashes before the quotes and before the dollar sign, but nothing fixes it.

Any ideas what I’m doing wrong?

Advertisement

Answer

Inside single quotes all symbols except ' lose their special meaning. Therefore $( ) is not interpreted yet. If it was interpreted, you could nest quotes. But since it isn’t interpreted, you cannot nest quotes.

Your alias is basically

'some literal string 'anUnquotedString' another literal string'

The unquoted string r is the same as r.

Using a function instead of an alias solves the quoting issues easily.

stop() {
  screen -R BedrockServer -X stuff "stop $(printf 'r')"
}

If you want to stick to an alias, there are many options to get the quoting right, for instance

alias stop="screen -R BedrockServer -X stuff "stop $(printf '\r')""

Both commands from above execute printf each time you execute stop. This is not necessary. In the alias, you can execute it once for the definition (note the missing before $( )):

alias stop="screen -R BedrockServer -X stuff "stop $(printf 'r')""

And for the function and/or alias, you even can drop printf entirely by using an ANSI C string:

stop() {
  screen -R BedrockServer -X stuff $'stop r'
}
alias stop=$'screen -R BedrockServer -X stuff "stop r"'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement