Kevin
Kevin

Reputation: 6831

Unix shell to prompt user for filename

please pardon since I am a UNIX beginner.

I wanna write a shell script that can ask user type in the filename and output the number of lines in that file, here is my code:

echo "Pls enter your filename:"
read filename
result=wc -l $filename

echo "Your file has $result lines"

However, I couldn't get it working since it complains about the identifier "filename". Could experts help?Thanks !!

Upvotes: 3

Views: 18855

Answers (3)

paxdiablo
paxdiablo

Reputation: 882146

That works fine, at least in bash. Well, the read works fine. However, the assignment to result should probably be:

result=$(wc -l $filename)

but, since that command outputs both the line count and the filename, you might want to change it a little to just get the line count, something like:

result=$(cat $filename | wc -l)

or:

result=$(wc -l <$filename)

The command you have:

result=wc -l $filename

will set result to the literal wc, then try to execute the -l command.

For example, the following five-line script:

#!/bin/bash
echo "Pls enter your filename:"
read filename
result=$(cat $filename | wc -l)
echo "Your file has $result lines"

will, when run and given its name as input, produce the following:

Your file has 5 lines

If you're not using bash, you need to specify which shell you are using. Different shells have different ways of doing things.

Upvotes: 6

Drona
Drona

Reputation: 7234

Here you go :

echo "Pls enter your filename:" 
read filename 
result=`wc -l $filename | tr -s " " | cut -f2 -d' '`

echo "Your file has $result lines"

Upvotes: 1

nos
nos

Reputation: 229224

If you want to evaluate wc -l $filename , you have t do:

result=$(wc -l $filename)

Otherwise, with result=wc -l $filename, bash will assign wc to result, and interpret the next word(-l) as a command to run.

Upvotes: 1

Related Questions