Bonz0
Bonz0

Reputation: 373

Using grep inside shell script gives file not found error

I cannot believe I've spent 1.5 hours on something as trivial as this. I'm writing a very simple shell script which greps a file, stores the output in a variable, and echos the variable to STDOUT.

I have checked the grep command with the regex on the command line, and it works fine. But for some reason, the grep command doesn't work inside the shell script.

Here is the shell script I wrote up:

#!/bin/bash

tt=grep 'test' $1
echo $tt

I ran this with the following command: ./myScript.sh testingFile. It just prints an empty line.

Upvotes: 10

Views: 25162

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85873

You need to use command substitution:

#!/usr/bin/env bash

test=$(grep 'foo' "$1")
echo "$test"

Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed like this:

$(command)

or like this using backticks:

`command`

Bash performs the expansion by executing COMMAND and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting.

The $() version is usually preferred because it allows nesting:

$(command $(command))

For more information read the command substitution section in man bash.

Upvotes: 16

Related Questions