rt3x.de NoPaste

Get the content of an environment variable

This is a nopaste service, powered by Flying Paste.

Author: Malte Bublitz
Language/File type: Bash script

Description

Various ways to get an environment variable on the command line, more or less unnecessary complicated.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env bash

# The boring default way: echo
echo $PWD

# A bit less boring: pwd(1)
pwd

# printf(1)
printf "%s\n" "$PWD"

# printenv(1)
printenv PWD

# Here string
cat <<<"$PWD"

# AWK
awk 'BEGIN {print ENVIRON["PWD"]}'

# Python
python3 -c 'import os;print(os.getenv("PWD"))'

# PHP
php -r 'print getenv("PWD") . "\n";'

# Perl
perl -E 'say $ENV{PWD}'

# Tcl
echo 'puts $::env(PWD)' | tclsh

# PowerShell Core
pwsh -NoProfile -Command 'Write-Host $env:PWD'

# Insane: Python reads variable name from stdin and calls awk to retrieve it
echo "PWD" | python3 -c 'import subprocess,sys;
var = sys.stdin.read().strip();
print(subprocess.run(
    ["awk", "BEGIN {print ENVIRON[\"" + var + "\"]}"],
    stdout=subprocess.PIPE).stdout.decode("UTF-8"))'