Home > Mobile >  How do you convert characters to ascii without use of the printf in bash
How do you convert characters to ascii without use of the printf in bash

Time:11-27

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)

CodePudding user response:

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).

  • Related