0

I'm trying to write a shell script that outputs the nth line from a file called file.txt, but I keep getting various errors; one of them including

Line 7: [: 10 file.txt: integer expression expected

and so I cant seem to make it work. What am I doing wrong?

# Read from the file file.txt and output the tenth line to stdout.
#!/bin/bash

len=`wc -l file.txt`
echo $len

if [ "$len" -lt 10 ]
then
    errormessage="File too short"
    echo $errormessage
    exit 0
fi

var=`sed '10q;d' file.txt`
echo $var
  • 2
    Try typing `wc -l file.txt` into your shell. What do you see? Is it just a number? – rici Jun 08 '18 at 18:43
  • 1
    Capturing the output to a variable so you can output it is obviously redundant. – tripleee Jun 08 '18 at 18:47
  • @triplee: If you are going to do it, you better quote the expansion. – rici Jun 08 '18 at 18:48
  • 1
    @Devam: A lot of the issues in your script(s) could be detected by passing them through https://shellcheck.net. It's usage is *highly* recommended. – rici Jun 08 '18 at 18:48
  • Yeah, I was just going to post another comment with a link to https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable – tripleee Jun 08 '18 at 18:49
  • Also see [How to use Shellcheck](https://github.com/koalaman/shellcheck), [How to debug a bash script?](https://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](https://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](https://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Jun 08 '18 at 19:37
  • Having `#!/bin/bash` anywhere in the file other than the first line makes the system use your default shell. Hopefully `bash` in your case. – alvits Jun 09 '18 at 01:56

3 Answers3

1

wc -l file... prints the number of lines and the filename for each filename listed as an argument

If no filenames are listed, wc -l reads from standard input and just prints the number of lines.

In short, use

len=$(wc -l < file.txt)

Note the redirection so that stdin is used instead of naming the file on the command line.

And try to completely forget that backticks exist: their usage has been deprecated for aeons. Use the $(...) syntax as shown.

rici
  • 234,347
  • 28
  • 237
  • 341
0

Instead of just giving wc -l file.txt give cat file.txt | wc -l. the latter one will return only the number of lines whereas the first one will return the number lines with the file name next to it.

sriramsm04
  • 343
  • 1
  • 7
  • 22
0

Show the tenth line or give an error message and exit:
I will use exit 1, since 0 is normallly ok.
However, in order to have a special returncode for sed, I will make sed return 1 for a match.

errormessage="File too short"
var=$(sed -n '10 {p;q1}' file.txt) && { echo "${errormessage}"; exit 1; }
# You must have spaces above the pipes |    |                       |  |
Walter A
  • 19,067
  • 2
  • 23
  • 43