简体   繁体   中英

How can I pipe to a bash alias from an npm script?

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?

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM