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

chicks
  • 2,393
  • 3
  • 24
  • 40
  • Check **iconv**. More is here: [https://stackoverflow.com/questions/11303405/force-encode-from-us-ascii-to-utf-8-iconv](https://stackoverflow.com/questions/11303405/force-encode-from-us-ascii-to-utf-8-iconv) – Andrzey Nov 26 '21 at 22:08
  • 1
    FYI, your function isn't valid syntax as currently shown in the question -- it needs a bit more syntax. `ascii() { printf '%d' "'$1"; }` -- note the added spaces and `;`, necessary for a one-liner function declaration. – Charles Duffy Nov 26 '21 at 22:35
  • VAR=$(ascii $CHAR|awk '{print $4}') – ufopilot Nov 27 '21 at 00:30
  • If you've only been using `bash` for a few hours, then it's not too late to start using a language that's probably more appropriate for your actual task. – chepner Nov 27 '21 at 15:49

2 Answers2

5

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

M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • 2
    The `printf -v` version is, while less portable, significantly more efficient; it's worth calling out that there are practical advantages to using it, instead of potentially leaving it implied that the two alternatives are practically equivalent. (Real David Korn ksh93 optimizes away the subshell when you do the `var=$(printf ...)` thing, but at least as of this writing, bash does not). – Charles Duffy Nov 26 '21 at 21:46
-1

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"
macemurez
  • 29
  • 5