1

This is my simple shell script

root@Ubuntu:/tmp# cat -n script.sh 
     1  echo
     2  while x= read -n 1 char
     3  do
     4   echo -e "Original value = $char"
     5   echo -e "Plus one = `expr $char + 1`\n"
     6  done < number.txt
     7  echo
root@Ubuntu:/tmp# 

And this is the content of number.txt

root@Ubuntu:/tmp# cat number.txt 
12345
root@Ubuntu:/tmp#

As you can see on the code, I'm trying to read each number and process it separately. In this case, I would like to add one to each of them and print it on a new line.

root@Ubuntu:/tmp# ./script.sh 

Original value = 1
Plus one = 2

Original value = 2
Plus one = 3

Original value = 3
Plus one = 4

Original value = 4
Plus one = 5

Original value = 5
Plus one = 6

Original value = 
Plus one = 1


root@Ubuntu:/tmp# 

Everything looks fine except for the last line. I've only have 5 numbers, however it seems like the code is processing additional one.

Original value = 
Plus one = 1

Question is how does this happen and how to fix it?

1 Answer 1

1

It seems the input file number.txt contains a complete line, which is terminated by a line feed character (LF). (You can verify the input file is longer than 5 using ls -l.) read eventually encounters the LF and gives you an empty char (stripping the terminating LF from the input as it would without the -n option). This will give you expr + 1 resulting in 1. You can explicitely test for the empty char and terminate the while loop using the test -n for non-zero length strings:

echo "12345" | while read -n 1 char && [ -n "$char" ]; do echo "$char" ; done
Sign up to request clarification or add additional context in comments.

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.