2

I am trying to invert an 8 bit Binary number using bash and shell script making 1 0 and vice versa then save the new variable, turning 10101010 into 01010101.

input=10101010
echo $input 
echo $Input | tr 01 10

will give me

10101010
01010101

but does not allow me to save this to a new variable if i try:

invertedInput=$Input | tr 01 10

How can I get this right?

codeforester
  • 39,467
  • 16
  • 112
  • 140
Dave
  • 41
  • 1
  • 5
  • backticks... check process interpolation. – Jason Hu Nov 09 '17 at 18:23
  • or $() https://stackoverflow.com/questions/9449778/what-is-the-benefit-of-using-instead-of-backticks-in-shell-scripts – Daniel Gale Nov 09 '17 at 18:32
  • 1
    question : do you want this to work on 'binary' numbers, the answer below does not work for 00111001 11000110 – wwright Nov 09 '17 at 23:40
  • I think you would have to use "bc" to work on binary number and apply [hexnumber] (https://stackoverflow.com/questions/40667382/how-to-perform-bitwise-operations-on-hexadecimal-numbers-in-bash) [convertion hex] ( https://stackoverflow.com/questions/11120324/hex-to-binary-conversion-in-bash) – wwright Nov 09 '17 at 23:46

2 Answers2

2

Use x=$(cmd) to capture the output of a command and assign it to a variable.

In addition, as a good practice, use cmd <<< ... instead of echo ... | cmd when passing the content of a variable to the standard input of a command.

Like this:

input=10101010
invertedInput=$(tr 01 10 <<< "$input")
echo "$invertedInput"
# prints: 01010101
janos
  • 120,954
  • 29
  • 226
  • 236
  • Why do you consider Here String better practice than using echo? – virullius Nov 09 '17 at 18:35
  • @mjb2kmn `echo` is an extra process. Here String is a native feature. It's faster. – janos Nov 09 '17 at 18:51
  • 2
    Although the pipeline with `echo` does induce a subshell/`clone`, the [here-string uses a temporary file](https://unix.stackexchange.com/questions/219804/resource-usage-using-pipe-and-here-string) (unlinked after pipes are set-up). So the [speed actually depends](https://unix.stackexchange.com/a/219806/232065) on the size of the data passed (along with fs setup, etc). In `bash`, *`tr <<< data` is usually faster for smaller chunks of data, and `echo data | tr` is faster for bigger chunks*. – randomir Nov 09 '17 at 21:52
2

you just need to wrap the output of your expression with $( )

invertedInput=$(echo $input | tr 01 10)

echo $invertedInput

01010101
tritium_3
  • 648
  • 1
  • 8
  • 17