Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash bug re $LINENO-- or am I just confused?

Tags:

bash

shell

sh

Consider:

#!/bin/bash

echo '
' $LINENO
echo '' '
'  $LINENO

The first echo correctly prints a 4, but the second echo prints a 5 instead of 6. Am I missing something, or is this a bug? (Using bash 3.00.15)

like image 610
William Pursell Avatar asked Jun 15 '11 16:06

William Pursell


People also ask

How do I know if bash script is running successfully?

Now, every command run in bash shell returns a value that's stored in the bash variable “$?”. To get the value, run this command. $ echo $? If a command succeeded successfully, the return value will be 0.

What does [[ ]] mean in bash?

The [[ ... ]] part allows to test a condition using operators. Think of it as an if statement. In your example, you're using the -s operator, which tests that the referenced file is not empty. Copy link CC BY-SA 3.0.

Does bash echo?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

What does D mean in bash?

In bash command -d is to check if the directory exists or not. For example, I having a directory called. /home/sureshkumar/test/. The directory variable contains: "/home/sureshkumar/test/"


2 Answers

It looks like an implementation misfeature (bug) in bash.

I used:

#!/bin/bash -p
echo $LINENO
echo ' ' $LINENO '
' $LINENO '
' $LINENO
echo '' '
'  $LINENO

which yielded:

2
  3 
 3 
 3

 6

Which supports the theory that the variable is evaluated before the shell considers the line to have been completed. Once the line has been completed, it updates the LINENO and proceeds.

Bash versions tested: 3.2.48 (mac), 4.1.5 (linux)

When I use the syntax:

echo '
' $LINENO

it gets the newer line number. It seems to be related to the evaluation of the empty string carried as the only argument on the line.

like image 161
Petesh Avatar answered Sep 28 '22 14:09

Petesh


Bash seems to interpret a multi-string & multi-line argument to the echo command to be on just one line of the source code file (script) because Bash has to concatenate the multi-string & multi-line argument to the echo command into a single (one line) argument. The concatenation mechanism is also triggered by an empty string '' followed by a string containing a newline character echo -e '' + '\n' + $LINENO.

#!/bin/bash
# Bash concatenates a multi-string & multi-line argument ...
echo ' ' $LINENO '
' $LINENO '
' $LINENO

# ... into a one line argument.
echo -e "' ' $LINENO '\n' $LINENO '\n' $LINENO\n"

#!/bin/bash
echo "2
3
4
5
6 LINENO: $LINENO"   # 6 LINENO: 6
exit

#!/bin/bash
echo "2" " " "
3
4
5
6 LINENO: $LINENO"   # 6 LINENO: 2
# echo -e "2" + " " + "\n3\n4\n5\n6 LINENO: $LINENO"
exit
like image 21
chaz Avatar answered Sep 28 '22 16:09

chaz