如何在 NodeJS 脚本中加载自定义 bash 别名?

How load custom bash aliases in NodeJS script?

我有bash脚本

#!/bin/bash
shopt -s expand_aliases
. my_custom_aliases # load aliases
alias foo # show alias definition
foo # run alias

它正在按我想要的方式工作

$ ./alias.sh 
alias foo='echo barrr'
barrr

但现在我想在 nodejs 脚本中做同样的事情。

我用 ShellJS 包尝试过类似的东西

#! /usr/bin/env node
var shell = require("shelljs");
shell.exec('shopt -s expand_aliases', {shell: '/bin/bash'});
shell.exec('. my_custom_aliases', {shell: '/bin/bash'});
shell.exec('alias foo', {shell: '/bin/bash'});
shell.exec('foo', {shell: '/bin/bash'});

(my_custom_aliases明明是在同一个目录)

但它只会让我感到震惊

$ node am.js 
/bin/bash: line 0: alias: foo: not found
/bin/bash: foo: command not found

所以我的问题是:如何从文件加载自定义别名并能够在节点脚本中使用它们?

我不相信你在做理智的事情(如果你真的这样做,无论如何函数可能比别名更好),但问题是你运行正在使用四个独立的shells,每一个然后退出并失去你创建的任何状态。

对于运行单身shell,你想要

shell.exec('shopt -s expand_aliases \n . my_custom_aliases \n alias foo; foo',
  {shell: '/bin/bash'});

如以下评论所述,因为 expand_aliases 需要在首次解析带有别名的行时处于活动状态,所以您需要换行符而不是分号作为第一和第二个语句分隔符。