我正在寻找一个简单的命令,允许我从命令行为另一个命令创建一个终端别名,最好使用它而不必重启我的终端。
用例如下,我刚刚创建了一个小的bash脚本并将其放在gist上。
# Babel in your project
npm i json -g
npm install --save-dev babel-core babel-cli babel-preset-es2015 babel-preset-react
json -f package.json -I -e 'this.scripts.test = "mocha --compilers js:babel-core/register --recursive"'
json -f package.json -I -e 'this.babel = {}'
json -f package.json -I -e 'this.babel.presets = ["es2015", "react"]'
json -f package.json -I -e 'this.main = "./lib/index"'
json -f package.json -I -e 'this.esnext = "./src/index"'
我可以在这里从终端运行它:
bash -c "$(curl -fsSL https://gist.githubusercontent.com/reggi/8035dcbdf0fb73b8c8703a4d244f15cf/raw/767ec8c2fb54b554ce122cc85953da5b277dbaf4/babel-ready.sh)"
我很好奇是否可以轻松地从终端创建alias
。简单的事情:
add-alias babel-ready -- bash -c "$(curl -fsSL https://gist.githubusercontent.com/reggi/8035dcbdf0fb73b8c8703a4d244f15cf/raw/767ec8c2fb54b554ce122cc85953da5b277dbaf4/babel-ready.sh)"
答案 0 :(得分:0)
粗略尝试(不是流控制感知,不是幂等,不能识别和删除相同别名的旧版本)可能看起来像这样:
# non-POSIX-compliant function keyword used to allow dash in function name
function add-alias() {
# declare locals explicitly to prevent scope leakage
local content_line cmd
(( $# == 1 )) && [[ $1 ]] || {
echo "Usage: add_alias name" >&2
return 1
}
IFS= read -r content_line
# reject inputs containing newlines
content_line=${content_line%$'\n'}
if [[ $content_line = *$'\n'* ]]; then
echo "ERROR: Only one line may be provided" >&2
return 1
fi
# generate a command
printf -v cmd "alias %q=%q" "$1" "$content_line"
# eval it in the local shell, and add to the rc if that succeeds
eval "$cmd" && printf '%s\n' "$cmd" >>"$HOME/.bashrc"
}
...用作:
add-alias babel-ready <<'EOF'
bash -c "$(curl -fsSL https://gist.githubusercontent.com/reggi/8035dcbdf0fb73b8c8703a4d244f15cf/raw/767ec8c2fb54b554ce122cc85953da5b277dbaf4/babel-ready.sh)"
EOF
注意使用<<'EOF'
- 引用heredoc很重要,因为这可以防止在定义别名时运行扩展(而不是在运行时)。这就是为什么用法是在stdin上而不是在命令行上传递代码的原因,这将使用户有责任适当地引用命令行参数。