将以下 bash 脚本转换为 sh

Convert the follwing bash script to sh

我有这个脚本:

#!/bin/sh
while IFS= read -r -d "" f; do
    ary+=("$f")
done < <(find ~/project/jobs -maxdepth 1 -mindepth 1 -type d -not -name "utils" -printf "\"%f\"[=11=]")

(IFS=","; echo "[${ary[*]}]")

应该列出 my_folder 的顶级文件夹,但名为 exclude 的文件夹除外。 它是在 bash 中制作的,但我正在执行它的机器上没有 bash。

这导致给我错误:

(On line 3) Syntax error: word unexpected (expecting ")")

我想在 sh 中转换它以便能够执行它。

我放在https://www.shellcheck.net/

它给了我错误:

Line 4:
while IFS= read -r -d "" f; do
                   ^-- SC2039: In POSIX sh, read -d is undefined.

Line 5:
    ary+=("$f")
    ^-- SC2039: In POSIX sh, += is undefined.
         ^-- SC2039: In POSIX sh, arrays are undefined.

Line 6:
done < <(find ~/project/jobs -maxdepth 1 -mindepth 1 -type d -not -name "utils" -printf "\"%f\"[=12=]")
       ^-- SC2039: In POSIX sh, process substitution is undefined.

Line 8:
(IFS=","; echo "[${ary[*]}]")
                 ^-- SC2039: In POSIX sh, array references are undefined.

有没有办法把它转换成 sh ?我将如何进行。

您根本不需要 find。由于 POSIX 不支持任意数组,您可以使用位置参数代替它们。

#!/bin/sh

set --   # Clear the positional parameters
cd ~/project/jobs

for d in */; do
  [ "$d" = "utils/" ] && continue
  set -- "$@" "\"${d%/}\""
done

(IFS=","; printf '[%s]\n' "$*")

如果脚本要立即退出,您可以去掉括号,因为全局设置 IFS 不会有任何坏处。


您似乎正在尝试生成 JSON,如果完全可以安装 jq,我会推荐以下内容:

cd ~/project/jobs
jq -n --args '$ARGS.positional | select(.!="utils/") | map(rtrimstr("/"))' */

如果我们只是想转换原始脚本,这里是:

#!/bin/sh
find ~/project/jobs -maxdepth 1 -mindepth 1 -type d -not -name "utils" -printf "\"%f\"\n" | { \
sep=
while read -r f; do
    ary="$ary$sep$f"
    sep=,
done
echo "[$ary]"
}

解释

我们使用管道 (|) 而不是进程替换。

此外,我们还必须将 while 循环与最终回显组合在一起。