Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question
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 at 13:23
    
What's wrong with killall tomcat? –  Chris S Mar 11 at 13:31
    
Or pkill tomcat... –  ewwhite Mar 11 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 at 14:13

3 Answers 3

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'
share|improve this answer

You can "glue" single quotes with double quotes :

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

Here is an interesting reference : http://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.

share|improve this answer
1  
Or you can use a backslash to escape them. –  Jenny D Mar 11 at 13:16
    
@Jenny D Tried to escape them with backslash but didn't worked : unexpected EOF.... –  krisFR Mar 11 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: gnu.org/software/bash/manual/bashref.html#Single-Quotes –  glenn jackman Mar 11 at 13:22

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=`'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.