Method to ls and awk directory contents into a shell variable

1

I'm struggling to find some way to express this in some other fashion that will yield the appropriate output:

var="$(ls /var/run/ | grep searchterm | awk {'NR == 2'})"

I've seen on places like shellcheck to use a glob or loop but my research so far hasn't come up with anything to do it so that I can get the result as a variable rather than just echoing or printing the content.

Are there any methods to do this?

Jarrad S

Posted 2016-12-10T04:15:30.713

Reputation: 13

What is your end goal that you wish to accomplish with capturing this information into a shell variable? If you edit and expand your question to cover why you want to do this, the answer may become clearer. Thank you. – StandardEyre – 2016-12-10T04:23:19.970

It is part of a custom Icinga plugin I am writing for myself.

There is 4 files in the directory - 3 have static names - 1 doesn't. I need to evaluate the contents of these files for the plugin.

The non-statically named file does have some part of the file name that is static to itself and separate from the rest which is what the grep searchterm is.

The variable itself is used to take some other actions later. – Jarrad S – 2016-12-10T04:26:47.790

(1) Why are you doing NR == 2?  (2) If you use awk, you should put the entire awk program in quotes; e.g., '{NR == 2}', with the curly braces inside the quotes. – G-Man Says 'Reinstate Monica' – 2016-12-17T03:23:58.720

Answers

0

var="$( find /var/run -iregex "$YOUR_REGEX" 2> /dev/null )"

Of course, man find to learn some limitations of the -iregex option.

If the searchterm is not too complex, you might use -iname "*$SEARCHTERM*" instead.

In general, parsing the output of ls is something you really should avoid.

pepoluan

Posted 2016-12-10T04:15:30.713

Reputation: 962

1This worked. I had to use a -type flag as well, but it worked out. – Jarrad S – 2016-12-12T11:38:18.193

0

If your situation is

There are four files in the directory — three have static names (e.g., red, blue and green) and one doesn’t.  But I know that the fourth one will have foo in its name.  I want to get that fourth filename.  Obviously, I can safely search for foo, because none of the static names contain foo.

then all you need to do is

var="$(echo /var/run/*foo*)"

If you’re just working in the current directory, and you do

var="$(echo *foo*)"

and the fourth filename might begin with a - (dash), the above can fail.  (Also, either of the above commands can fail if the filename might contain \ (backslash).)  But

var="$(printf '%s' *foo*)"

or

var="$(printf '%s' /var/run/*foo*)"

should work.

Of course, if the fourth filename might begin with a . (dot), you have another problem.

G-Man Says 'Reinstate Monica'

Posted 2016-12-10T04:15:30.713

Reputation: 6 509