0

I want to know how I can put the contents of a variable in a text file. This variable is a string that I want the code with the base64 command.But this command only works on files. I wonder if there are other possibilities for this task

1
  • 1
    Have you tried echoing? echo $var > file.txt Commented Apr 9, 2015 at 10:34

3 Answers 3

3

You don't need a text file, you can use this:

base64 <<< "$var"

or

echo "$var" | base64

Example:

var="abcde"
base64 <<< "$var"

results

YWJjZGUK
1

You can use Here Strings. It is supported by bash, zsh and other common shells.

Example: The grep command only work with files but here we are passing a variable using Here Strings to be searched for pattern by grep.

$ str="this is a test line"
$ grep -o "test" <<< "$str"
test

As far as your command is concerned you can use:

$ base64 <<< "$str"
1

Your question suggests that you want to base64 encode the content of a variable:

$ TEXT=test
$ ENCODED=$(echo "$TEXT" | base64)
$ echo "$ENCODED"
dGVzdAo=
2
  • 2
    "$var" and ${var} are not the same. Choose the former to avoid word splitting and glob expansion. Commented Apr 9, 2015 at 10:47
  • correct, updated. Commented Apr 9, 2015 at 10:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.