"${x%% *}" 在 sh 中是什么意思?

Gal*_*axy 4 shell shell-script variable

我刚刚在 makefile 中看到了“$${x%% *}”,这意味着 sh 中的“${x%% *}”。为什么这样写?

makefile 如何检测本地计算机中是否有命令可用?

determine_sum = \
        sum=; \
        for x in sha1sum sha1 shasum 'openssl dgst -sha1'; do \
          if type "$${x%% *}" >/dev/null 2>/dev/null; then sum=$$x; break; fi; \
        done; \
        if [ -z "$$sum" ]; then echo 1>&2 "Unable to find a SHA1 utility"; exit 2; fi

checksums.dat: FORCE
    $(determine_sum); \
    $$sum *.org
Run Code Online (Sandbox Code Playgroud)

frn*_*ntn 9

这是一个 POSIX shell 变量替换功能:

${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var.
${var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $var.
Run Code Online (Sandbox Code Playgroud)

因此,如果 var="abc def ghi jkl"

echo "${var% *}" # will echo "abc def ghi"
echo "${var%% *}" # will echo "abc"
Run Code Online (Sandbox Code Playgroud)

  • 不仅仅是`bash`,由POSIX `sh` 指定。参见 Shell 命令语言中的[参数扩展](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02)。 (2认同)