Konstantin Grushetsky
Konstantin Grushetsky

Reputation: 1062

Why can't gulp-shell set environment variables?

I have the following simple gulpfile.js script:

var gulp = require('gulp');
var shell = require('gulp-shell');

gulp.task('run-me', shell.task([
  'export sweet_param=5',
  'echo $sweet_param'
]));

The problem is that $sweet_param variable is not printed.

When run on Windows 8.1 under Git Bash it fails with the message:

[16:51:06] Starting 'run-me'...
'export' is not recognized as an internal or external command,
operable program or batch file.
[16:51:06] 'run-me' errored after 29 ms
[16:51:06] Error in plugin 'gulp-shell'
Message:
    Command `export sweet_param=5` failed with exit code 1

In case of Linux the task is executed without errors but the blank line is printed instead of expected value:

[16:49:32] Starting 'run-me'...

[16:49:32] Finished 'run-me' after 26 ms

If the commands from the task are executed manually in bash on both operating systems, 5 is successfully echoed.

Software used:

What's the catch here?

Thank you!

Upvotes: 0

Views: 2143

Answers (1)

ddprrt
ddprrt

Reputation: 7574

Bash allows environment variables only to exist during one bash session. When you type

export sweet_param=5

sweet_param just exists as long as the bash is open. Close your shell, and sweet_param's gone.

gulp-shell takes a command per line, but for every line, it boots up another bash: open bash >> execute line >> terminate bash >> next. Therefore, after every line you have there, all the previously set params are gone.

Try:

gulp.task('run-me', shell.task([
   'export sweet_param=5 && echo $sweet_param'
]));

to see that if you have all the executions in one line, your parameters will sta.

To write it a little more pretty, you could use something like that:

gulp.task('run-me', shell.task([
   'export sweet_param=5',
   'echo $sweet_param'
].join(' && '));

As for the Win problem: Git bash is still no Unix shell. You should try Cygwin or consorts to make that work.

Upvotes: 4

Related Questions