LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash BC problem (https://www.linuxquestions.org/questions/programming-9/bash-bc-problem-873160/)

mcfc1900 04-05-2011 01:24 PM

Bash BC problem
 
My line of code which isn't working is the following:

variable=$(ibase=16; $hex | bc)

I have also tried:

variable=$(echo "ibase=16; $hex" | bc)

Neither will work and gives me the error "(Standard_in) 1: parse error".

$hex has been defined two lines above this piece of code...

Can anyone see where I am going wrong please?

Thanks

Kenhelm 04-05-2011 02:38 PM

The error message could be caused by the letters in $hex not being in upper case.
Lower case letters are used for variable names in bc.
Code:

hex=45de
echo "ibase=16; $hex" | bc
(standard_in) 1: parse error

hex=45DE
echo "ibase=16; $hex" | bc
17886


Telengard 04-05-2011 02:49 PM

Quote:

Originally Posted by mcfc1900 (Post 4314843)
variable=$(ibase=16; $hex | bc)

I can't see how you expect that to work. Assuming $hex holds a valid hexadecimal value, ibase=16; $hex needs to be supplied to bc on its standard input. The | (pipe) implies that some other program will be emitting the program from its standard output.

This works fine for me.

Code:

foo$ hex=10
foo$ variable=$(echo "ibase=16; $hex" | bc)
foo$ echo $variable
16
foo$

I think we will need to see more of your program to determine the cause of your error.

Edit
Quote:

Originally Posted by Kenhelm (Post 4314920)
The error message could be caused by the letters in $hex not being in upper case.
Lower case letters are used for variable names in bc.

Nice catch! :)

mcfc1900 04-05-2011 03:52 PM

Thank you both :)

The problem was that the hex value was lower case, soon as I changed that it started working.

Cheers

Nominal Animal 04-05-2011 03:57 PM

Quote:

Originally Posted by mcfc1900 (Post 4314843)
variable=$(echo "ibase=16; $hex" | bc)

Why not use
Code:

variable=$[0x$hex]


All times are GMT -5. The time now is 12:56 PM.