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?

Luis
  • 1

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,231
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
  • 79,293
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
  • 48,171
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