Basically i'd like to assign to variable $finalbyte a value (which consists of a binary representation of a byte e.g 11100000). So trying to do that i put the following as part of some script:

field4=224     ##224 for example, it could be any number.
               ##Depends on the script

finalbyte=$(echo 'obase=2; ibase=10; ${field4}' | bc)   ##<-------error here

I get the following error which is kinda like obvious to interpret but my problem is that i don't know or imagine the way that $field4 could nestle down there in between the other arguments . The error is:

(standard_in) 1: illegal character: $
  • I consider your question as typo in using "${field4}" variable. When you use 'this' quotes , contents is not interpreted. If you use "this" quotes , contents is interpreted. Additionally I would put whole $(...) into brackets finalbyte="$(...)". Finally, I consider this question as not good fit for unix.se as it's about too basic problem - typo - of syntax. – Grzegorz Wierzowiecki Jul 2 '13 at 19:56

Use double-quotes instead of single-quotes. Parameters are not substituted inside single-quotes

 finalbyte=$(echo "obase=2; ibase=10; ${field4}" | bc)

Also, if you are on bash, you may prefer here-strings to command substitution for this case:

bc <<<"obase=2; ibase=10; ${field4}"
  • Don't need triple quotes in bash. You have a leading empty string, the bc script and then a trailing empty string. – glenn jackman Jul 3 '13 at 0:21

move your variable outside of the quoted arg to echo:

$ field4=224 finalbyte=$(echo 'obase=2; ibase=10;' ${field4}| bc )
$ echo $finalbyte

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.