0

I am trying to write a shell script that asks a user for number of lines they would like to display from a file and then display those lines.

I am trying to do this via the following:

#!/bin/bash 
#author = johndoe


read -p "How many lines from /c/Users/johndoe/files/helpme.sh would you like to see? " USERLINEINPUT

LINE_NUM=1

while [ $LINE_NUM -lt $USERLINEINPUT ]
do 

    echo "$LINE_NUM: $USESRLINEINPUT"
    ((LINE_NUM++))

done < /c/Users/johndoe/files/helpme.sh 

This code doesn't appear to do as I'd like, please see an example below:

    $ ./linecount.sh
How many lines from /c/Users/johndoe/files/helpme.sh would you line to see? 10
1:
2:
3:
4:
5:
6:
7:
8:
9:
3
  • 1
    Hi, Suppose you enter 10, should your program print 10 lines from helpme.sh? Commented Feb 20, 2018 at 15:58
  • hi, yes it should print the line numbers from 1 to 10 and the content for each line Commented Feb 20, 2018 at 15:58
  • I have provided a solution below please check. Commented Feb 20, 2018 at 16:09

2 Answers 2

1

Your code does not satisfy your requirement. You need to read each line of code into a variable and print it. Your while loop is only satisfy with user input value and you are not printing the file line at all. See the correct code below and see you mistakes. Hope this will help you:-

#!/bin/bash
#author = johndoe

LINE_NUM=1
read -p "How many lines from /c/Users/johndoe/files/helpme.sh would you like to see? " USERLINEINPUT
while read -r line
do
     echo "$LINE_NUM:$line"
     if [ $LINE_NUM -ge $USERLINEINPUT ]; then
        break;
     fi
     ((LINE_NUM++))
done < "/c/Users/johndoe/files/helpme.sh"
Sign up to request clarification or add additional context in comments.

Comments

0
#!/usr/bin/env bash

# file will be the first argument or helpme.sh by default
file=${1:-/c/Users/johndoe/files/helpme.sh}    

# exit if the file is NOT readable
[[ -f $file && -r $file ]] || exit 1

# ask for a number and exit if the input is NOT a valid number
IFS= read -r -p "Number of lines from \"$file\": " num
[[ $num =~ ^[0-9]+$ ]] || exit 2

# 1st option: while/read 
count=
while IFS= read -r line && ((count++<num)); do
    printf '%d:%s\n' "$count" "$line"
done < "$file"

# 2nd option: awk
awk 'NR>ln{exit}{print NR":"$0}' ln="$num" "$file"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.