bash alias command with both single and double quotes

LinuxBashQuotesDouble Quotes

Linux Problem Overview


I have this command that does what I want but I can't get to alias it in my .bashrc (note that it uses both single and double quotes):

svn status | awk '$1 =="M"{print $2;}'

I've tried:

alias xx="svn status | awk '$1 ==\"M\"{print $2;}'"

And some other common sense combinations with no luck.. I know that bash is very picky with quotes.. So what's the correct way to alias it and why ? Thanks

Linux Solutions


Solution 1 - Linux

You just need to escape it correctly.

alias xxx="svn status | awk '\$1 ==\"M\"{print \$2;}'"

Solution 2 - Linux

Here's something that accomplishes the same thing without using an alias. Put it in a function in your .bashrc:

xx() {
    svn status | awk '$1 =="M"{print $2;}'
}

This way you don't have to worry about getting the quotes just right. This uses the exact same syntax you would at the command line.

Solution 3 - Linux

Since Bash 2.04 there is a third (easier) way beside using a function or escaping the way @ffledgling did: using string literal syntax (here is an excellent answer).

So for example if you want to make an alias of this onliner it will end up being:

alias snap-removedisabled=$'snap list --all | awk \'$5~"disabled"{print $1" --revision "$3}\' | xargs -rn3 snap remove'

So you just have to add the $ in front of the string and escape the single quotes.

This brings a shellcheck warning you could probably safely disable with # shellcheck disable=SC2139.

Solution 4 - Linux

You can revert the double and simple quotations, so that double quotations are outside of single quotations.

For example, this does not work:

alias docker-table='docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Status}}"'

But this works:

alias docker-table="docker ps --format 'table {{.ID}}\t{{.Image}}\t{{.Status}}'"

And when you check the actual alias interpreted, you can see the inner quotations are actually escaped.

$ alias docker-table
alias docker-table='docker ps --format '\''table {{.ID}}\t{{.Image}}\t{{.Status}}'\'''

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpragmatic_programmerView Question on Stackoverflow
Solution 1 - LinuxffledglingView Answer on Stackoverflow
Solution 2 - LinuxEJKView Answer on Stackoverflow
Solution 3 - LinuxPablo BianchiView Answer on Stackoverflow
Solution 4 - LinuxWesternGunView Answer on Stackoverflow