Roger Herling
Roger Herling

Reputation: 9

assign number value to alphabet in shell/bash

I have a script that prompts for the user to enter a 3 letter code. I need to convert that code to a number that corresponds to a=01, b=02....etc for the first two letters of that code.
For example the user enters ABC for $SITECODE I need to take the A&B and convert it to 0102 and store it to a new variable.

#!/bin/bash


# enable logging
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>/var/log/ULFirstBoot.log 2>&1

###################################### global variables ######################################################

# top level domain
tld="somedomain.com"

# grabs the serial number for ComputerName
serial=`/usr/sbin/system_profiler SPHardwareDataType | /usr/bin/awk '/Serial\ Number\ \(system\)/ {print $NF}'`

# Cocoadialog location
CD="/Users/Shared/cocoaDialog.app/Contents/MacOS/cocoaDialog"


################################################### Begin Define Functions ####################################################

userinput () # Function will promt for Username,SItecode, and Region using Cocoadialog
{
    # Prompt for username
rv=($($CD inputbox --title "User Name" --no-newline --informative-text "Please Enter the Users Employee ID" --icon "user" --button1 "NEXT" --button2 "Cancel"))

USERNAME=${rv[1]}

if [ "$rv" == "1" ]; then
    echo "`date` User clicked Next"
    echo "`date` Username set to ${USERNAME}"
    elif [ "$rv" == "2" ]; then
    echo "`date` User Canceled"
    exit
fi

# Dialog to enter the User name and the create $SITECODE variable
rv=($($CD inputbox --title "SiteCode" --no-newline --informative-text "Enter Site Code" --icon "globe" --button1 "NEXT" --button2 "Cancel"))

SITECODE=${rv[1]} #truncate leading 1 from username input 


if [ "$rv" == "1" ]; then
    echo "`date` User clicked Next"
    echo "`date` Sitecode set to ${SITECODE}"
    elif [ "$rv" == "2" ]; then
    echo "`date` User Canceled"
    exit
fi

# Dialog to enter the Password and the create $REGION variable
rv=($($CD dropdown --title "REGION" --text "Choose Region" --no-newline --icon "globe" --items NA EULA AP --button1 "OK" --button2 "Cancel"))

item=${rv[1]}


if [[ "$rv" == "1" ]] 
    then echo "`date` User clicked OK"
    elif [[ "$rv" == "2" ]] 
        then echo "`date` User Canceled"
        exit
fi

if [ "$item" == "0" ]; then
    REGION="NA"
    echo "`date` Region set to NA"
    elif [ "$item" == "1" ]; then
    REGION="EULA"
    echo "`date` Region set to EULA"
    elif [ "$item" == "2" ]; then
    REGION="AP"
    echo "`date` Region Set to AP"
fi


# Confirm that settings are correct

rv=($($CD msgbox --text "Verify settings are correct" --no-newline --informative-text "USER-$USERNAME REGION-$REGION, SITE CODE-$SITECODE" --button1 "Yes" --button2 "Cancel"))

if [[ "$rv" == "1" ]]
    then echo "`date` User clicked OK"
    elif [[ "$rv" == "2" ]] 
        then echo "`date` User Canceled"
        exit
fi


}

# Sets computername based
setname ()
{
    ComputerName=$SITECODE$serial

    /usr/sbin/scutil --set ComputerName $SITECODE$serial  
    echo "`date` Computer Name Set to" $(/usr/sbin/scutil --get ComputerName)
    /usr/sbin/scutil --set LocalHostName $SITECODE$serial
    echo  "`date` LocalHostname set to" $(/usr/sbin/scutil --get LocalHostName)
    /usr/sbin/scutil --set HostName $SITECODE$serial.$tld
    echo "`date` Hostname set to" $(/usr/sbin/scutil --get HostName)

}

adbind () 
{
    OU="ou=Computers,ou=${SITECODE}Win7,ou=$REGION,dc=global,dc=ul,dc=com"
    echo "`date` OU will be set to $OU"
    dsconfigad -add "global.ul.com" -username "user" -password "password" -ou "$OU" 
    dsconfigad -mobile "enable" -mobileconfirm "disable" -groups "Domain Admins, ADMIN.UL.LAPTOPADMINS"
}

# Checks if machine is succesfully bound to AD before proceeding
adcheck () 
{
    until [ "${check4AD}" = "Active Directory" ]; do
    check4AD=`/usr/bin/dscl localhost -list . | grep "Active Directory"`
    sleep 5s 
    done
}

adduser () # creates mobile user account based on userinput function
{
    # create mobile user account and home directory at /Users/username
    /System/Library/CoreServices/ManagedClient.app/Contents/Resources/createmobileaccount -n $USERNAME -h /Users/$USERNAME 
    # Add newly created user to local admins group
    dscl . -append /Groups/admin GroupMembership $USERNAME
    # set login window to show username and password promts not a list of users
    defaults write /Library/Preferences/com.apple.loginwindow SHOWFULLNAME 1
}

setADMPass ()
{
        parsed1=${SITECODE:0:1}
parsed2=${SITECODE:1:1}
}

####################################### End define Functions ####################################################


############################################# Bgin Main Script #######################################################

userinput
setname
adbind
adcheck
adduser
echo $(dscl . -read /Groups/admin GroupMembership)
echo $(defaults 'read' /Library/Preferences/com.apple.loginwindow.plist SHOWFULLNAME)
# Reboot to apply changes
shutdown -r now "Rebooting to enable Mobile accounts"

Upvotes: 0

Views: 2501

Answers (3)

AKS
AKS

Reputation: 17326

see if this helps! BASH 4+. If you find any issues, that'd be your homework.

#!/bin/bash

declare -A koba
i=1

for vi in {a..z};do koba=(["$vi"]="0${i}"); ((i++)); done
for vi in {A..Z};do koba=(["$vi"]="0${i}"); ((i++)); done

echo -en "\nEnter a word: "; read w; w="$( echo $w | sed "s/\(.\)/\1 /g" | cut -d' ' -f1,2)";

new_var="$(for ch in $w; do echo -n "${koba["${ch}"]}"; done)";

echo $new_var;

Upvotes: 0

Roger Herling
Roger Herling

Reputation: 9

I found the answer thanks for all your help!

setADMPass ()
    {
        alower=abcdefghijklmnopqrstuvwxyz

        site=$(echo $SITECODE | tr '[:upper:]' '[:lower:]')
        parsed1=${site:0:1}
        parsed2=${site:1:1}

        tmp1=${alower%%$parsed1*}     # Remove the search string and everything after it
        ch1=$(( ${#tmp1} + 1 ))

        tmp2=${alower%%$parsed2*}     # Remove the search string and everything after it
        ch2=$(( ${#tmp2} + 1 ))

        if [[ $ch1 -lt 10 ]]; then
            #statements
            ch1=0$ch1
        fi

        if [[ $ch2 -lt 10 ]]; then
            #statements
            ch2=0$ch2
        fi

        passpre=$ch1$ch2


    }

Upvotes: 0

gniourf_gniourf
gniourf_gniourf

Reputation: 46833

Here's a funny way to do your encoding, abusing Bash's arithmetic:

string2code() {
    # $1 is string to be converted
    # return variable is string2code_ret
    # $1 should consist of alphabetic ascii characters, otherwise return 1
    # Each character is converted to its position in alphabet:
    # a=01, b=02, ..., z=26
    # case is ignored
    local string=$1
    [[ $string = +([[:ascii:]]) ]] || return 1
    [[ $string = +([[:alpha:]]) ]] || return 1
    string2code_ret=
    while [[ $string ]]; do
        printf -v string2code_ret '%s%02d' "$string2code_ret" "$((36#${string::1}-9))"
        string=${string:1}
    done
}

Try it:

$ string2code abc; echo "$string2code_ret"
010203
$ string2code ABC; echo "$string2code_ret"
010203

The magic happens here:

$((36#${string::1}-9))

The term 36# tells Bash that the following number is expressed in radix 36. In this case, Bash considers the characters 0, 1, ..., 9, a, b, c, ..., z (ignoring case). The term ${string:1} expands to the first character of string.

Upvotes: 1

Related Questions