0

I've been trying to save in a variable the value of the convert of a number from decimal to binary, like this:

num1=10
echo "obase=2;$num1" | bc   | tee -a register.txt

but I don't want to show it in screen, because the idea is just do the convert and save it in the file like register.txt

How can I do so?

Mike Pierce
  • 737
  • 1
  • 6
  • 23
Luis
  • 1
  • Add a `>/dev/null` at the end. `num1=10; echo "obase=2;$num1" | bc | tee -a register.txt >/dev/null` – Valentin Bajrami Oct 22 '14 at 05:38
  • possible duplicate of [Can a bash script be hooked to a file?](http://unix.stackexchange.com/questions/5515/can-a-bash-script-be-hooked-to-a-file) – PersianGulf Oct 22 '14 at 05:58
  • Your original question had `num` = 10`, you should leave out the spaces. Also don't ask if someone can help, that can be answered by "yes"/"or" and doesn't solve your real problem. – Anthon Oct 22 '14 at 06:01

4 Answers4

2

You can do it using the output redirection as below.

$ bc -l <<<"obase=2;$num" > register.txt

The above command will overwrite any older results. In case if you want to append your results.

$ bc -l <<<"obase=2;$num" >> register.txt

>> - Redirects output (STDOUT) messages in append mode.

> - Redirects output (STDOUT) messages in overwrite mode.

<<< - Here Strings, The word is expanded and supplied to the command on its standard input.

Kannan Mohan
  • 3,191
  • 2
  • 17
  • 16
1

The tee command is there to split the output, most often used to get text to a file and to the screen.

Just leave it out and use output redirection (appending) to file with >>:

echo "obase=2;$num1" | bc >> register.txt
Anthon
  • 78,313
  • 42
  • 165
  • 222
0

Instead of using tee, just use I/O-Redirection of the shell:

echo "obase=2;$num1" | bc >>register.txt

The >>-statement causes the output to be redirected (> redirect, >> append) to the file. The -a flag of tee causes also an append to the file. You only need tee if you want the output to be shown in the shell AND redirected to a file.

chaos
  • 47,463
  • 11
  • 118
  • 144
0

Note that if your shell is ksh or zsh, you don't need bc to convert to binary¹.

in ksh/zsh:

$ typeset -i2 num1=10
$ print -- "$num1"
2#1010
$ print -- "${num1#??}"
1010

With zsh:

$ print -- $(( [##2] num1 ))
1010

(zsh doesn't do split+glob upon parameter expansions or arithmetic expansions, so you don't need to quote them, though quoting won't harm).

With ksh93:

$ num1=10
$ printf '%..2d\n' "$num1"
1010

With any of those, add > register.txt to redirect that output into a file (replacing its contents, if any), or >> register.txt to append it to the file (like tee -a does; though tee also writes its input to its stdout).


¹ unless the number doesn't fit in a 64 bit integer

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501