gpt4 book ai didi

javascript - package.json 脚本中的 Node 支持哪些类似 shell 的语法?

转载 作者:行者123 更新时间:2023-12-05 04:21:26 27 4
gpt4 key购买 nike

在我的 Node package.json 脚本中,我可以使用一些简单的 shell 语法:

scripts: {
detect-cheese: "echo 'Is there cheese?' $($* | grep -q cheese && echo yep || echo nope)"
}
$ yarn run detect-cheese apple cheese banana
Is there cheese? yep

但这似乎是 Bash(或其他一些 shell 的)语法的一个子集。例如,可选参数很难做到:

scripts: {
fox: "echo fox $1",
cat: "echo cat ${1-Rufus}"
}

$ yarn run fox
Unbound argument #1
$ yarn run cat Chester
Unbound variable "1-Rufus"

这种类似于 shell 的语法的详细信息是否记录在某处?

最佳答案

npm 和 yarn v1

类 unix 系统上的 shell 是 sh 所以坚持 POSIX sh definitions .

sh 中 null 或未定义值的默认值是 ${VAR:-default}

cat: "echo \"cat ${1:-Rufus}\""

yarn 2+ 浆果

使用最小的 sh 实现 yarnpkg-shell它支持基本的 shell 语法,但不完全符合 POSIX。这使得所有环境,无论是否有 sh,都能够以相同的方式执行 package.json 脚本。


测试运行以下内容:

printf 'VAR=  %s\n' "$VAR"
printf 'VAR- %s\n' "${VAR-def}"
printf 'VAR:- %s\n' "${VAR:-def}"
printf 'VAR+ %s\n' "${VAR+def}"
printf 'VAR:+ %s\n' "${VAR:+def}"

通过:

{
"name": "so36729207-npm-sh",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"sh": "printf 'VAR= %s\n' \"$VAR\"; printf 'VAR- %s\n' \"${VAR-def}\"; printf 'VAR:- %s\n' \"${VAR:-def}\"; printf 'VAR+ %s\n' \"${VAR+def}\"; printf 'VAR:+ %s\n' \"${VAR:+def}\""
}
}

在 dash/Debian、ash/Alpine 和 zsh/macos 环境中为 sh 生成相同的结果

$ docker run --rm so36729207/alpine npm run sh      

> so36729207-npm-sh@1.0.0 sh
> printf 'VAR= %s
> ' "$VAR"; printf 'VAR- %s
> ' "${VAR-def}"; printf 'VAR:- %s
> ' "${VAR:-def}"; printf 'VAR+ %s
> ' "${VAR+def}"; printf 'VAR:+ %s
> ' "${VAR:+def}"

VAR=
VAR- def
VAR:- def
VAR+
VAR:+
$ docker run --rm --env VAR= so36729207/alpine npm run sh

> so36729207-npm-sh@1.0.0 sh
> printf 'VAR= %s
> ' "$VAR"; printf 'VAR- %s
> ' "${VAR-def}"; printf 'VAR:- %s
> ' "${VAR:-def}"; printf 'VAR+ %s
> ' "${VAR+def}"; printf 'VAR:+ %s
> ' "${VAR:+def}"

VAR=
VAR-
VAR:- def
VAR+ def
VAR:+
$ docker run --rm --env VAR=a so36729207/alpine npm run sh

> so36729207-npm-sh@1.0.0 sh
> printf 'VAR= %s
> ' "$VAR"; printf 'VAR- %s
> ' "${VAR-def}"; printf 'VAR:- %s
> ' "${VAR:-def}"; printf 'VAR+ %s
> ' "${VAR+def}"; printf 'VAR:+ %s
> ' "${VAR:+def}"

VAR= a
VAR- a
VAR:- a
VAR+ def
VAR:+ def

关于javascript - package.json 脚本中的 Node 支持哪些类似 shell 的语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74208814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com