Omegaspard
Omegaspard

Reputation: 1980

Convert the follwing bash script to sh

I have this script:

#!/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\"\0")

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

That is supposed to list the top level folder of the my_folder except the one named exclude. It is made in bash, but I don't have bash on the machine I'm executing it.

Which result in giving me the error :

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

I would like to convert it in sh so I would be able to execute it.

I put it on https://www.shellcheck.net/

and it gave me the errors :

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\"\0")
       ^-- SC2039: In POSIX sh, process substitution is undefined.

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

Is there a way to convert it to sh ? How would I proceed.

Upvotes: 0

Views: 670

Answers (2)

Philippe
Philippe

Reputation: 26850

If we just wanted to convert the original script, here it is :

#!/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]"
}

Explain

Instead of process substitution, we use piping (|).

Also we have to group while-loop with the final echo.

Upvotes: 1

chepner
chepner

Reputation: 532418

You don't really need find for this at all. Since POSIX doesn't support arbitrary arrays, you can use the positional parameters in their place.

#!/bin/sh

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

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

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

If the script is going to exit immediately, you can drop the parentheses, as there won't be any harm in setting IFS globally.


As it appears you are trying to generate JSON, I would recommend the following if installing jq is at all an option:

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

Upvotes: 2

Related Questions