1

I tried to make alias with quotes as following:

alias myalias='ps -ef | grep tomcat | kill -9 `awk {'print $2'}`'

but as you can see i already have ' in awk

so i tried to replace

awk {'print $2'}

with

awk {"print $2"}

but then strange things happen to me when i run this alias, ie, the console window get closed... how can i make this alias work

Jas
  • 701
  • 4
  • 13
  • 23
  • 3
    It is customary to put awk's {braces} inside the quotes, but not strictly required. awk requires its program to be a single command line argument. You could write, if you were sufficiently perverse: `awk {print\ \$2}` – glenn jackman Mar 11 '14 at 13:23
  • What's wrong with `killall tomcat`? – Chris S Mar 11 '14 at 13:31
  • Or `pkill tomcat`... – ewwhite Mar 11 '14 at 14:11
  • `killall` doesn't always do what you think it does, so I think it's a bad habit to get into. (On some unixes, it is the equivalent of `shutdown`...) – Jenny D Mar 11 '14 at 14:13

4 Answers4

9

Using a function instead of an alias avoids most of these quoting problems:

myfn() { ps -ef | awk '/tomcat/ {print $2}' | xargs kill -9; }

If you're using awk, don't need grep.

Or, stick with a function and avoid almost all the work you're doing:

alias myalias='pkill -9 -f tomcat'
glenn jackman
  • 4,630
  • 1
  • 17
  • 20
4

You can "glue" single quotes with double quotes :

alias myalias='ps -ef | grep tomcat | kill -9 `awk {'"'"'print $2'"'"'}`'

Here is an interesting reference : https://stackoverflow.com/questions/1250079/escaping-single-quotes-within-single-quoted-strings

However, there are simpler solutions to kill a process instead of using multiple pipes or additional single quotes (Cf others answers). Here i was just trying to answer your initial question, keeping your logic.

krisFR
  • 13,280
  • 4
  • 36
  • 42
  • 1
    Or you can use a backslash to escape them. – Jenny D Mar 11 '14 at 13:16
  • @Jenny D Tried to escape them with backslash but didn't worked : `unexpected EOF....` – krisFR Mar 11 '14 at 13:18
  • @JennyD, you cannot escape single quotes in a single quoted string. `x='foo\'bar'` does not work. You have to do something like `x='foo'\''bar'`. Ref: http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes – glenn jackman Mar 11 '14 at 13:22
4

Here are the essentials for alias quoting:

alias x='echo dollar sign: \$ "single quote: '\'' backslash: \\ double quote: \"."'
$ alias x
alias x='echo dollar sign: \$ "single quote: '\'' backslash: \\ double quote: \"."'
$ x
dollar sign: $ single quote: ' backslash: \ double quote: ".

There is very little that cannot be done, virtually anything that can be typed on the bash command line can be put into an alias.

1

Instead of running these multiple pipes, use arguments to ps to get only the pid to start with:

alias killtc='kill `ps -C tomcat -o pid=`'
Jenny D
  • 27,780
  • 21
  • 75
  • 114