0

I have this string:

address 0 address-set hostname-of-a-host

and this grep command:

file=`/bin/grep -ilr ".*$host_name.*" /path/to/some/files/*

Where:

host_name=`echo $line | cut -d ' ' -f 4-`

I want to get the host_name and if in a path files that contains it.

So, this is the code:

line="address 0 address-set hostname-of-a-host"
host_name=`echo $line | cut -d ' ' -f 4-`
file=`/bin/grep -ilr ".*$host_name.*" /path/to/some/files/*

These commands works in a shell without issues. However, the script returns an empty "file" variable. I don't know why they don't work in script but works in shell.

This is the output on a bash execution (i' m sorry but i have to modify :

root@cpm:/path/# line="address 0 address-set hostname"
root@cpm:/path/# host_name=`echo $line | cut -d ' ' -f 4-`
root@cpm:/path/# file=`/bin/grep -ilr ".*$host_name.*" /path/to/some/files/*
root@cpm:/path/# echo $file
/path/to/some/files/file1
testrDev
  • 17
  • 8
Miguel.G
  • 377
  • 1
  • 6
  • 20
  • 1
    Some closing backquotes are missing. – Renaud Pacalet Jul 29 '21 at 09:24
  • 1
    I'd recommend putting `set -x` before the problem section of the script, so it'll print a trace of what's happening (e.g. what `host_name` is getting set to, what's being passed to `grep`, etc), and see if it matches what you expect. Note: it's normal for the quoting/escaping to look weird, since it may choose different (but equivalent) quotes/escapes to what you'd type in to get the same result (see [this question](https://stackoverflow.com/questions/52526289/bash-adding-extra-single-quotes-to-curl-command-defined-as)). But if the things *in* quotes are weird, that'll tell you something. – Gordon Davisson Jul 29 '21 at 09:26
  • Okay, that was a very simple but useful idea. There was an \r in each line, so strings didn't match due to that. Thank you. – Miguel.G Jul 29 '21 at 11:09

2 Answers2

0

There was a \r char at the fianl of each line. With set -x was clear.

Miguel.G
  • 377
  • 1
  • 6
  • 20
  • I thought that might be it. Files with DOS/Windows line endings cause all sorts of weird problems with unix tools. Anyway, glad you got it sorted. – Gordon Davisson Jul 29 '21 at 11:19
-1

you could use eval, eval takes a string and runs it as a command, just like if it was entered on the shell command line. This includes all quote and expansion processing, as long as you are not using user input, because if the user inputs with single quotes, they could break out of the quoting and run arbitrary commands

an example of using eval

host_name=`echo $line | cut -d ' ' -f 4-`
eval "$host_name"
Shaqil Ismail
  • 1,794
  • 1
  • 4
  • 5
  • 1
    This doesn't help, and just creates new problems. The original would work if not for the file format. This won't work anyway, because it tries to run the hostname as a command, and it isn't one. – Gordon Davisson Jul 29 '21 at 11:23