Question: I have a set of valid characters [0-9a-z\_] and a variable that is assigned one of these characters. What I want to do is to be able to increment that variable to the next in the set.

If need be I can handle the "special" cases where it would increment from '9' to 'a' and 'z' to '\_', but I can't figure out how to increment letters.

```
#!/bin/bash
y=b
echo $y  # this shows 'b'
y=$((y+1))
echo $y  # this shows '1', but I want it to be 'c'

```

Answer: 
**for those who would like to print incremented letter by execution of a function**:

```
ALPHA=( {A..Z} ) 
alpha_increment () { echo ${ALPHA[${i:-0}]}; ((i++)) ;}

```

---

```
alpha_increment
A
alpha_increment
B
alpha_increment
C

```
I wrote this for a project, it uses the chr and ord fucntions(also found here somewhere) and some pure bash(only external called in the function is tr), if you are doing more than 100 characters I would use something else, but for short strings in my testing its actually slightly faster than python. 
Also this script lower cases any input, you will have to modify it for upper case. 
after putting these functions in your script(or cut and paste into a shell) you can just do

inc\_string abz9z9

and get back. 

aca0a0

```
chr() {
  [ "$1" -lt 256 ] || return 1
  printf "\\$(printf '%03o' "$1")"
}

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

inc_string () 
{
string="$1";
lcstring=$(echo $string | tr '[:upper:]' '[:lower:]');

for ((position=$((${#lcstring}-1));position>=0;position--));do  

  if [ "${lcstring:position:1}" = 'z' ]; then
    if [ "$position" -eq "$((${#lcstring}-1))" ]; then
       newstring="${lcstring:0:$(($position))}a";
       lcstring="$newstring";
    elif [ "$position" -eq "0" ]; then 
       newstring="a${lcstring:$((position+1))}";
       echo $newstring;
       break;
    else
       newstring="${lcstring:0:$(($position))}a${lcstring:$((position+1))}";
       lcstring="$newstring";
    fi
  elif [ "${lcstring:position:1}" = '9' ]; then
    if [ "$position" -eq "$((${#lcstring}-1))" ]; then
       newstring="${lcstring:0:$(($position))}0";
       lcstring="$newstring";
    elif [ "$position" -eq "0" ]; then  
       newstring="0${lcstring:$((position+1))}";
       echo $newstring;
       break;
    else
       newstring="${lcstring:0:$(($position))}0${lcstring:$((position+1))}";
       lcstring="$newstring";
    fi  
  else
    if [ "$position" -eq "$((${#lcstring}-1))" ]; then
       newstring="${lcstring:0:$(($position))}$(chr $(($(ord ${lcstring:position})+1)))";
       echo $newstring;
       break;
    elif [ "$position" -eq "0" ]; then
       newstring="$(chr $(($(ord ${lcstring:position})+1)))${lcstring:$((position+1))}";
       echo $newstring;
       break;
    else
       newstring="${lcstring:0:$(($position))}$(chr $(($(ord ${lcstring:position})+1)))${lcstring:$(($position+1))}";
       echo $newstring;
       break;               
    fi
  fi
done

}

```