firepro20 firepro20 - 7 months ago 43
Bash Question

Assign ASCII values to variable in shell

I'm still new at shell scripting

I want to assign * to a variable an print it. Write now I'm just printing it with:

echo -e "\052"


Is there a way to assign that value to a variable?

Answer

Use $(cmd) or `cmd` to capture a command's output. The $(...) form is preferred because it's easier to nest.

var=$(echo -e "\052")

The shell will interpret escape sequences inside $'...'. That's single quotes with a dollar sign in front.

var=$'\052'

Or of course you could write the asterisk directly. Quote it to prevent wildcard expansion.

var='*'

When you print it, make sure to quote the variable. It's annoying to always have to type double quotes any time you use a variable, but it's usually the right thing to do.

echo "$var"    # yes
echo $var      # no
Comments