From bba147f18531934c904b1c5afaed3e6550b1c1c0 Mon Sep 17 00:00:00 2001 From: Stefan Mesken Date: Sun, 14 Jun 2020 01:01:41 +0200 Subject: [PATCH] read environment variable (#604) * read environment variable * set default config path --- src/os.md | 4 ++++ src/os/external.md | 2 ++ src/os/external/read-env-variable.md | 25 +++++++++++++++++++++++++ 3 files changed, 31 insertions(+) create mode 100644 src/os/external/read-env-variable.md diff --git a/src/os.md b/src/os.md index efef2c1..14f3873 100644 --- a/src/os.md +++ b/src/os.md @@ -7,11 +7,15 @@ | [Run piped external commands][ex-run-piped-external-commands] | [![std-badge]][std] | [![cat-os-badge]][cat-os] | | [Redirect both stdout and stderr of child process to the same file][ex-redirect-stdout-stderr-same-file] | [![std-badge]][std] | [![cat-os-badge]][cat-os] | | [Continuously process child process' outputs][ex-continuous-process-output] | [![std-badge]][std] | [![cat-os-badge]][cat-os][![cat-text-processing-badge]][cat-text-processing] | +| [Read environment variable][ex-read-env-variable] | [![std-badge]][std] | [![cat-os-badge]][cat-os] | + [ex-parse-subprocess-output]: os/external.html#run-an-external-command-and-process-stdout [ex-parse-subprocess-input]: os/external.html#run-an-external-command-passing-it-stdin-and-check-for-an-error-code [ex-run-piped-external-commands]: os/external.html#run-piped-external-commands [ex-redirect-stdout-stderr-same-file]: os/external.html#redirect-both-stdout-and-stderr-of-child-process-to-the-same-file [ex-continuous-process-output]: os/external.html#continuously-process-child-process-outputs +[ex-read-env-variable]: os/external.html#read-environment-variable + {{#include links.md}} diff --git a/src/os/external.md b/src/os/external.md index 99fb2a5..a69a11c 100644 --- a/src/os/external.md +++ b/src/os/external.md @@ -10,4 +10,6 @@ {{#include external/continuous.md}} +{{#include external/read-env-variable.md}} + {{#include ../links.md}} diff --git a/src/os/external/read-env-variable.md b/src/os/external/read-env-variable.md new file mode 100644 index 0000000..f74894a --- /dev/null +++ b/src/os/external/read-env-variable.md @@ -0,0 +1,25 @@ +## Read Environment Variable + +[![std-badge]][std] [![cat-os-badge]][cat-os] + +Reads an environment variable via [std::env::var]. + +```rust,edition2018,no_run +use std::env; +use std::fs; +use std::io::Error; + +fn main() -> Result<(), Error> { + // read `config_path` from the environment variable `CONFIG`. + // If `CONFIG` isn't set, fall back to a default config path. + let config_path = env::var("CONFIG") + .unwrap_or("/etc/myapp/config".to_string()); + + let config: String = fs::read_to_string(config_path)?; + println!("Config: {}", config); + + Ok(()) +} +``` + +[std::env::var]: https://doc.rust-lang.org/std/env/fn.var.html