将数字值分配给shell / bash中的字母

时间:2014-12-15 17:01:00

标签: bash shell

我有一个脚本,提示用户输入3个字母的代码。我需要将该代码转换为与该代码的前两个字母对应a=01b=02 ....等的数字。
例如,用户为$SITECODE输入 ABC 我需要使用 A& B 并将其转换为 0102 并将其存储到一个新的变量。

#!/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"

3 个答案:

答案 0 :(得分:1)

这是一种有趣的编码方式,滥用Bash的算法:

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
}

试一试:

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

魔术发生在这里:

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

术语36#告诉Bash,以下数字以基数36表示。在这种情况下,Bash会考虑字符01,...,9abc,... 。,z(忽略大小写)。术语${string:1}会扩展为string的第一个字符。

答案 1 :(得分:0)

看看这有帮助! BASH 4+。如果您发现任何问题,那就是您的作业。

#!/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;

答案 2 :(得分:0)

我找到答案谢谢你的帮助!

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


    }