LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Using ASCII character codes in a shell script (Linux) (https://www.linuxquestions.org/questions/programming-9/using-ascii-character-codes-in-a-shell-script-linux-648583/)

Twelveone 06-11-2008 10:53 AM

Using ASCII character codes in a shell script (Linux)
 
Hi all,

After using the command "du -s $dir" to put the total size of a directory into a variable I want to strip the directory size out of the variable and loose the accompanying directory path.

To do this I've been trying to compare each character until I find the space between directory size and path and then ignore everything after it

When I compare the individual characters of a variable with " " (space) I find that any time a 0 (zero) appears it matches the " " (space). I think I should be able to use the ASCII character code for space, chr(32) to do the comparison but I don't know the syntax to allow this.

The command I'm using is simply: -

if [ "${char1}" -eq "${test}" ] ; then

where ${char1} is the first character of the variable and ${test} is the character against which it is compared.

Can anyone tell me how to do this?

Thanks

colucix 06-11-2008 11:45 AM

In bash there are different ways to manage ASCII codes. The echo command with option -e recognizes octal sequences, for example
Code:

echo -e "\0127"
prints out the character W. You can also assign a character to a variable given its octal code, for example
Code:

var=$'127'
will assign the character W to the variable var, or you can use this syntax directly in comparisons.

Anyway, for your specific problem you can simply do something like
Code:

du -s $dir | cut -d\t -f1
du -s $dir | awk '{print $1}'


A.Thyssen 02-07-2020 12:54 AM

An alternative is to not compare the characters but the character codes...

For example my "askpass_stars" script (reads a password while echoing stars)
http://www.ict.griffith.edu.au/antho...#askpass_stars
(See the bare minimum version 1)

This reads one character from the keyboard at a time, and converts it to a Hex code using...
Code:

  code=$(printf '%02x' "'$char'")
before figuring out what to do with the character in a shell "case" statement.
Note the use of extra single quotes within the double quotes!

ASIDE: watch out for unicode characters as this will produce non-ACSII character codes.
Code:

  printf '%02x\n' "'∞'"
  221e



All times are GMT -5. The time now is 04:45 AM.