How do you convert characters to ASCII without use of the printf in bash

Viewed 219
ascii() {printf '%d' "'$1"}

I am currently using this function to convert characters to ASCII, however I just want to store the result of the function as a variable without printing the ascii. How would I go about this? (please bear in mind I have only been using bash for a few hours total, so sorry if this is a dumb question.)

2 Answers

In bash, after

printf -v numval "%d" "'$1"

the variable numval (you can use any other valid variable name) will hold the numerical value of the first character of the string contained in the positional parameter $1.

Alternatively, you can use the command substitution:

numval=$(printf "%d" "'$1")

Note that these still use printf but won't print anything to stdout.

As stated in the comment by @Charles Duffy, the printf -v version is more efficient, but less portable (standard POSIX shell does not support the -v option).

Thx for your script! I didn't know how get ascii values so "'M" rescued me. I pass parameters to function to get return. Function returns I use to... Well, return err/status codes.

#!/bin/sh
# posix

ascii () {
    # $1 decimal ascii code return
    # $2 character
    eval $1=$(printf '%d' "'$2")
}

ascii cod 'M'

echo "'M' = $cod"
Related