user5382586
user5382586

Reputation:

Unable to stop reading in Shell Script

For a final project, I'm trying to create a shell script that will allow for easy user creation. The requirements include that I read information from a file and create a user based off of that. This is a snippet of code I'm having trouble with.

echo -n "Please provide a path to the file containing these parameters: "
read inputPath 

fileInfo = $(grep $inputPath) 

if [ -n "$fileInfo" ]; then 
    IFS="," read firstName lastName phoneNo emailAd < "$fileInfo" 
else
    echo "Cannot read, file is empty." >&2 
    exit 1
fi

After read inputPath It will not stop accepting input and continue onto the next line of code. I'm totally stumped.

Thanks for taking a look.

Upvotes: 2

Views: 111

Answers (1)

John1024
John1024

Reputation: 113834

This won't work at all as an assignment statement:

fileInfo = $(grep $inputPath) 

The shell does no allow spaces around = in an assignment. Even with we fix that problem, we will still have another:

fileInfo=$(grep $inputPath) 

If inputPath is a path with no spaces in it, then grep will look for that string in stdin and it will continue looking until you press ctrl-D to close stdin.

You demonstrate this by trying it at the command prompt:

$ inputPath=/usr/bin/python
$ grep $inputPath

The shell will wait for you to provide input.

Most likely, you wanted to search for something in the file whose name is $inputPath:

fileInfo=$(grep something "$inputPath") 

Note that we have quoted inputPath to prevent word splitting and pathname expansion.

More on the command with spaces

Let's look at this again:

fileInfo = $(grep $inputPath) 

If the shell sees this command, it will try to run the command fileInfo with first argument = and with the remaining arguments being the result of word splitting and pathname expansion on whatever $(grep $inputPath) produces. But, to do this, as Jonathan Leffler points out in the comments, the shell must first run grep $inputPath. As long as $inputPath does not contain whitespace, then grep will read stdin looking for text that matches the value of $inputPath. Unless ctrl-D is typed, the shell will appear to hang here.

In other words, even though the version of the command with the extra spaces has multiple problems, the first problem to be noticed will be that grep is waiting for stdin.

Upvotes: 2

Related Questions