Pregunta

I'm trying to write an alias for a common command to cancel a process, but I'm having issues with the single and double quotations. This is my first attempt at Bash scripting and I'm a bit stumped.

lsof -i tcp:80 | awk '$1 == "Google" {print $2}'

This works as a stand-alone command and outputs the correct PID.

When I try formatting it as an alias though I'm having issues. I know the command is stopping at the first single quote by the way this is structure but I'm not sure how to fix it.

alias test='lsof -i tcp:80 | awk '$1=="Google" {print $2}''
¿Fue útil?

Solución

There's no escape sequence for single quotes inside single quotes. You can't write \' like you might expect. So there are two options.

  1. You can break out of single quotes, add an escaped single quote \', and then go back in, like so:

    alias test='lsof -i tcp:80 | awk '\''$1 == "Google" {print $2}'\'
    
  2. You can use double quotes. You then have to escape not just the double quotes inside the string but also the dollar signs.

    alias test="lsof -i tcp:80 | awk '\$1 == \"Google\" {print \$2}'"
    

Otros consejos

Try defining your alias like this

alias test='lsof -i tcp:80 | awk '"'"'$1=="Google" {print $2}'"'"

The single quotes ' must be escaped between double quotes ". To do so, the command has to be split into several parts to escape them differently. lsof -i tcp:80 | awk '$1=="Google" {print $2}' can be split on single quotes like this

  1. lsof -i tcp:80 | awk
  2. '
  3. $1=="Google" {print $2}
  4. '

Then quote with appropriate quotes

  1. 'lsof -i tcp:80 | awk'
  2. "'"
  3. '$1=="Google" {print $2}'
  4. "'"

And merge every part together and you have your alias:

'lsof -i tcp:80 | awk'"'"'$1=="Google" {print $2}'"'"

Note that the first part does not contain any interpreted variable so it can be quoted with double quotes and merged with the second part. Thus the alias becomes

alias test="lsof -i tcp:80 | awk'"'$1=="Google" {print $2}'"'"

In almost every case where find yourself trying to define an alias, define a function instead.

testing () {
    lsof -i tcp:80 | awk '$1=="Google" {print $2}'
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top