0

My OS platform is this : SunOS machinehull01 5.10 Generic_148888-05 sun4v sparc SUNW,Sun-Fire-T200

I have written a shell script to run from a file

File name: test.sh

#!/bin/sh
VARNAME=$grep '-l' TestWord /home/hull/xml/text/*.txt
echo "Found $VARNAME"

When I run the above command in the console I'm getting the correct output without errors, But when I run sh test.sh or ./test.sh I'm getting below error

test.sh: -l: not found
Found

Can someone please help me on this?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
user360321
  • 177
  • 1
  • 4
  • 19

2 Answers2

3

You are searching for so called "command substitution" :

VARNAME=$(grep -l TestWord /home/hull/xml/text/*.txt)
echo "Found $VARNAME"

It will execute the command between $( and the closing parenthesis ) in a subshell and return the output of the command into VARNAME.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

Got it.

#!/bin/sh
VARNAME=`grep -l TestWord /home/hull/xml/text/*.txt`
echo "Found $VARNAME"

I had to put those (`)there.

user360321
  • 177
  • 1
  • 4
  • 19
  • 1
    This is the same answer that `hek2mgl` provided (backticks are an older version of `$(...)`, and should't be used in new code). – chepner Oct 27 '14 at 15:30
  • yeah but his solution is not working in Solaris, but this does. – user360321 Oct 31 '14 at 12:02
  • Oh, right, Solaris uses a non-POSIX shell (the actual Bourne shell, I think) for `/bin/sh`. You might consider switching to Solaris's POSIX shell, `/usr/xpg4/bin/sh`, if possible. – chepner Oct 31 '14 at 12:35