Test results:
BEFORE
x = 0, y =
y exists, z does not exist
RUNNING
function: 1 2 3
command: 4 5 6
no utility: x=7
AFTER
x = 0, y =
y exists, z does not exist
| # `env` that also supports fish functions | |
| function env | |
| set -l vars | |
| set -l vals | |
| set -l save_vars | |
| set -l save_vals | |
| set -l save_empty_vars | |
| # parse var=val pairs into `vars` and `vals` arrays | |
| set -l n 1 | |
| for arg in $argv | |
| if echo $arg | grep -q = | |
| set vars $vars (echo $arg | cut -d= -f1) | |
| set vals $vals (echo $arg | cut -d= -f2) | |
| set n (math $n + 1) | |
| else | |
| break | |
| end | |
| end | |
| if set -q argv[$n] | |
| # prepair new global environment, saving previous global vars | |
| for i in (seq (count $vars)) | |
| set -l var $vars[$i] | |
| set -l val $vals[$i] | |
| # save previous global var | |
| if set -qg $var | |
| if test -z $$var | |
| set save_empty_vars $save_empty_vars $var | |
| else | |
| set save_vars $save_vars $var | |
| set save_vals $save_vals $$var | |
| end | |
| end | |
| # set new global (for functions) and exported (for commands) var | |
| set -gx $var $val | |
| end | |
| # call command | |
| eval $argv[$n..-1] | |
| # clean up global variables | |
| for var in $vars | |
| set -eg $var | |
| end | |
| # restore previous global vars | |
| for i in (seq (count $save_vars)) | |
| set -g $save_vars[$i] $save_vals[$i] | |
| end | |
| for var in $save_empty_vars | |
| set -g $var | |
| end | |
| else # no utility to run | |
| # call `env` command to do the job | |
| command env $argv | |
| end | |
| end |
| # Tests | |
| # ===== | |
| function testfunction | |
| echo function: $x $y $z | |
| end | |
| function exist | |
| if set -qg $argv[1] | |
| echo exists | |
| else | |
| echo does not exist | |
| end | |
| end | |
| set x 0 | |
| set y | |
| echo BEFORE | |
| echo x = $x, y = $y | |
| echo y (exist y), z (exist z) | |
| echo RUNNING | |
| env x=1 y=2 z=3 testfunction | |
| env x=4 y=5 z=6 sh -c "'echo command: \$x \$y \$z'" | |
| echo 'no utility:' (env x=7 | grep x=) | |
| echo AFTER | |
| echo x = $x, y = $y | |
| echo y (exist y), z (exist z) |
Test results:
BEFORE
x = 0, y =
y exists, z does not exist
RUNNING
function: 1 2 3
command: 4 5 6
no utility: x=7
AFTER
x = 0, y =
y exists, z does not exist