dylanaraps / pure-sh-bible

📖 A collection of pure POSIX sh alternatives to external processes.
MIT License
6.45k stars 281 forks source link

Doing function in a subshell #54

Open ivbit opened 8 months ago

ivbit commented 8 months ago

Here https://github.com/dylanaraps/pure-sh-bible/#split-a-string-on-a-delimiter and in other examples: No need to restore the value of IFS, or to restore options. Use parentheses () instead of curly braces {} to run a function in a subshell. It will not pollute the environment.

split() ( 
    set -f
    IFS=$2
    set -- $1
    printf '%s\n' "$@"
)

Doing redirects before commands helps to avoid ambiguity:

>|listing.txt ls -lhAF
>|listing.txt echo Hello world
>|listing.txt 2>|errors.txt ls -lhAF

Some commercial Unix POSIX shell implementations require using $ variable reference in $(( )) arithmetic:

$ var=1
$ var=$(( $var + 2023 ))
$ printf '%s\n' "$var"

var=$((var+2023)) and : $((var+=2023)) will not work on those systems

I made some notes about portable POSIX-compliant shell scripting:

https://ivanb.neocities.org/blogs/y2024/posix