2

I'm working in tcsh. How do I create an alias for:

nc stop `nc list | awk '/Running/{print $1}'`

I tried various variations of:

alias ncstop "nc stop `nc list | awk '/Running/{print $1}'`"

but none work

  • Check out $() unix.stackexchange.com/a/165637/208146. I use bash, but I think it works in tcsh. – Stephen Rauch Jan 22 '17 at 15:36
  • In your alias, the backticks will be evaluated too early (ie: when the alias is defined). – Stephen Rauch Jan 22 '17 at 15:39
  • O.K. got it. what other way can I try to automate this cmd ? – galina korosov Jan 22 '17 at 15:46
  • In bash when i use ' (single quotes) in alias i always had trouble... awk works even with double quotes... give them a try. – George Vasiliou Jan 22 '17 at 15:59
  • 1
    As with many comments here I come from a bash background, but whenever aliases are tricky it's probably a sign you should use a function instead – Eric Renouf Jan 22 '17 at 16:05
1

You can change the quoting a bit to not allow the backticks to be evaluated until when the alias is used.

alias ncstop 'nc stop `nc list | awk '\''/Running/{print $1}'\''`'

This works because when the ' character is used for quoting, so that the special characters such as |, $ and the backtick are not interpreted by the shell. That allows those special characters to make it into the alias definition. But in the process of defining the alias the shell removes that outer layer of ''s. What actually ends up in the alias definition should be:

nc stop `nc list | awk '/Running/{print $1}'`

The '\'' construct can often use a little explaining. But in short it is three apostrophes. The first ends the previous quoted string, the next (which is escaped so as to not be interpreted by the shell) passes through, and the third starts another quoted string. So the '\'' construct allows an apostrophe (ie: ' or single quote) to appear inside of a single quoted string.

Getting all of the quotes and escapes right in a string that needs to traverse multiple layers of interpretation gets messy and complicated very quickly. There was a comment on the question that recommended (for bash) looking into implementing aliases as functions instead. I am pretty sure the same could be advised for tcsh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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