how to make alias with quotes

6,408

Solution 1

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'

Solution 2

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.

Solution 3

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.

Solution 4

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:
6,408

Related videos on Youtube

Jas
Author by

Jas

Updated on September 18, 2022

Comments

  • Jas
    Jas almost 2 years

    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

    • foxfabi
      foxfabi over 10 years
      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}
    • ewwhite
      ewwhite over 10 years
      Or pkill tomcat...
    • Jenny D
      Jenny D over 10 years
      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
    Jenny D over 10 years
    Or you can use a backslash to escape them.
  • krisFR
    krisFR over 10 years
    @Jenny D Tried to escape them with backslash but didn't worked : unexpected EOF....
  • foxfabi
    foxfabi over 10 years
    @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