Bash Print Env

Problem #7

Tags: middle shell bash

Who solved this?

No translations... yet

source: the dialog happened during interview for senior Java dev position at Huawei (in 2016 probably)

Q: How do you assess your knowledge of shell scripting?

A: I know some of it, but you'd better ask specific questions and judge yourself.

Q: Well... are there arrays, for example?

A: Eh... I'm sure I used them in bash and ksh, but I don't know if they are standard or extension.

Interviewer said there are no arrays by POSIX standard. And proposed the following short exercise:

Get a list of env variables. We want only their names (e.g. keys) - and only those, which consist of capital letters, digits and perhaps underscore, but starting with letter (also capital). This is to skip variables like _ etc.

So here is a task for you. Start with executing the command env - it will list all variables, keys and values, like this:

TMP=/tmp
SHELL=/bin/sh
rvm_prefix=/usr/share
USERNAME=zombi
_=echo

Be sure to solve Shell Commands first, however - to get acquainted with running bash in our sandbox.

Now you need to strip the "tails" of the lines, everything starting from equal sign for example. Probably learn to use sed tool for it. You'll need to "pipe" output of the first command to the second one, e.g. env | sed .... Or perhaps, awk?

Next we want to remove names which do not satisfy condition mentioned above. Perhaps, again find a suitable tool for it.

Sort them! Otherwise answer may fail to match!

Anyway, you'll have a list of names, separated with newlines after these manipulations. We want them to be separated with commas, for better visibility. For this you may want to learn something about arrays.

Example

In the case above, supposing it was the full output of env, with just 5 elements (usually there are more) result would be

SHELL,TMP,USERNAME
You need to login to get test data and submit solution.