Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script - is there any way converting number to char? [duplicate]

Tags:

bash

shell

Possible Duplicate:
Integer ASCII value to character in BASH using printf

I want to convert my integer number to ASCII character

We can convert in java like this:

int i = 97;          //97 is "a" in ASCII
char c = (char) i;   //c is now "a"

But,is there any way in to do this shell scripting?

like image 445
natrollus Avatar asked Oct 12 '12 09:10

natrollus


People also ask

What is $1 and $2 in shell script?

These are positional arguments of the script. Executing ./script.sh Hello World. Will make $0 = ./script.sh $1 = Hello $2 = World. Note. If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh .

What is $? In shell script?

• $? - exit status of command. • $$ - Check PID of current shell. • $! - check PID of last background Job. Below is an example.

How do I print an ascii character in bash?

It's possible to print this char by an octal code point by printing printf '\112' or echo $'\112' .


1 Answers

#!/bin/bash
# chr() - converts decimal value to its ASCII character representation
# ord() - converts ASCII character to its decimal value

chr() {
  printf \\$(printf '%03o' $1)
}

ord() {
  printf '%d' "'$1"
}

ord A
echo
chr 65
echo

Edit:

As you see ord() is a little tricky -- putting a single quote in front of an integer.

The Single Unix Specification: "If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote."

(Taken from http://mywiki.wooledge.org/BashFAQ/071).

See man printf(1p).

like image 144
Rahul Gautam Avatar answered Oct 12 '22 01:10

Rahul Gautam