| 1 |
--- |
| 2 |
short-description: Running external commands |
| 3 |
... |
| 4 |
|
| 5 |
# External commands |
| 6 |
|
| 7 |
As a part of the software configuration, you may want to get extra |
| 8 |
data by running external commands. The basic syntax is the following. |
| 9 |
|
| 10 |
```meson |
| 11 |
r = run_command('command', 'arg1', 'arg2', 'arg3', check: true) |
| 12 |
output = r.stdout().strip() |
| 13 |
errortxt = r.stderr().strip() |
| 14 |
``` |
| 15 |
|
| 16 |
If `check: true` is given, meson will error out if `command` returns with a |
| 17 |
non-zero exit code. Alternatively, you can set `check: false` and get the exit |
| 18 |
code with `r.returncode()`. |
| 19 |
|
| 20 |
Since 0.52.0, you can pass the command environment as a dictionary: |
| 21 |
|
| 22 |
```meson |
| 23 |
run_command('command', 'arg1', 'arg2', env: {'FOO': 'bar'}, check: true) |
| 24 |
``` |
| 25 |
|
| 26 |
Since 0.50.0, you can also pass the command [[@env]] object: |
| 27 |
|
| 28 |
```meson |
| 29 |
env = environment() |
| 30 |
env.set('FOO', 'bar') |
| 31 |
run_command('command', 'arg1', 'arg2', env: env) |
| 32 |
``` |
| 33 |
|
| 34 |
The `run_command` function returns an object that can be queried for |
| 35 |
return value and text written to stdout and stderr. The `strip` method |
| 36 |
call is used to strip trailing and leading whitespace from strings. |
| 37 |
Usually output from command line programs ends in a newline, which is |
| 38 |
unwanted in string variables. The first argument can be either a |
| 39 |
string or an executable you have detected earlier with `find_program`. |
| 40 |
|
| 41 |
Meson will autodetect scripts with a shebang line and run them with |
| 42 |
the executable/interpreter specified in it both on Windows and on |
| 43 |
Unixes. |
| 44 |
|
| 45 |
Note that you cannot pass your command line as a single string. That |
| 46 |
is, calling `run_command('do_something foo bar')` will not work. You |
| 47 |
must either split up the string into separate arguments or pass the |
| 48 |
split command as an array. It should also be noted that Meson will not |
| 49 |
pass the command to the shell, so any command lines that try to use |
| 50 |
things such as environment variables, backticks or pipelines will not |
| 51 |
work. If you require shell semantics, write your command into a script |
| 52 |
file and call that with `run_command`. |