7

I have an alias in my .bashrc for bunyan:

$ alias bsh
alias bsh='bunyan -o short'

This line runs fine in bash:

$ coffee src/index.coffee | bsh

But if I put the same thing in 'scripts'

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "coffee":"coffee src/index.coffee | bsh"
  },

And npm run coffee, it fails:

> coffee src/index.coffee | bsh

sh: bsh: command not found
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
  at exports._errnoException (util.js:870:11)
  at WriteWrap.afterWrite (net.js:769:14)

So at random I tried putting in || instead of | and it worked. I can't figure out why though. I don't have to escape pipe characters in JSON as far as I know.

However it doesn't actually pipe the output to the bsh alias.

The actual fix is to use "coffee":"coffee src/index.coffee | bunyan -o short" -- get rid of the alias completely.

How can I use a bash alias in an npm script?

jcollum
  • 43,623
  • 55
  • 191
  • 321
  • 2
    Don't; just write the full command out. Aliases are intended for interactive shells to save typing. In a script, you only have to type it once. Alias expansion is turned off by default in non-interactive shells, and while you can turn it on, there is still the problem that aliases are not inherited from other shells. – chepner May 18 '16 at 20:01

2 Answers2

5

You can create a function instead of an alias.

function bsh() {
    bunyan -o short
}
export -f bsh

The export will make it available to children processes.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
3

So I had a whole response typed up about using

. ~/.bash_aliases && coffee src/index.coffee | bsh

But it turns out that aliases are barely, if at all, supported in bash scripts. From what I have read, aliases are deprecated in favor of functions...

See this discussion for what convinced me to use functions instead of aliases. I tried for an hour or two to get aliases to work by testing with /bin/bash -c as well as npm run, with no luck. However, using a function as suggested by Diego worked immediately and without problems.

I am including this even though the question is already marked as answered in case someone as stubborn as me winds up here from google and decides to try to make aliases work instead of just using a function.

However, I did run into a problem specifically when trying to use this with npm scripts. Even with the export -f, my functions aren't recognized - I still had to manually include the bash_aliases file, and even then, I got an error about the -f option for export.

In order to actually get this working, I had to take out the function export line and manually include the bash_aliases file...

Community
  • 1
  • 1
  • The error from `export -f` sounds like you were running the script with `sh` instead of `bash`. See also https://stackoverflow.com/questions/5725296/difference-between-sh-and-bash – tripleee Jan 31 '18 at 17:34