1. 程式人生 > >[Bash] 分支、迴圈、陣列

[Bash] 分支、迴圈、陣列

分支

#!/bin/bash
read mychar
if [ "$mychar" == 'y' -o "$mychar" == 'Y' ];then
    echo YES
elif [ "$mychar" == "n" -o "$mychar" == "N" ];then
    echo NO
fi

迴圈和陣列:替換國家名稱的首字母為圓點

#!/bin/bash
#https://www.hackerrank.com/challenges/bash-tutorials-remove-the-first-capital-letter-from-each-array-element/problem?h_r=next-challenge&h_v=zen
read country
idx=0
while [ -n "$country" ]
do
    arr[idx]="$country"
    read country
    let idx+=1
done

#echo ${arr[*]}

length=${#arr[@]}

for((i=0;i<length;i++))
do
    myvar=${arr[i]}
    echo -n "."${myvar:1}" "
done

陣列的下標和陣列的值:找出一個不配對的陣列元素

#!/bin/bash
#https://www.hackerrank.com/challenges/lonely-integer-2/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
read N
read Line

arr=($Line)

for e in ${arr[@]}
do
    if [ -z "${cnt[e]}" ]; then
        cnt[e]=1
    else
        let cnt[e]+=1
    fi
done


#echo "${cnt[@]}"

#echo ${!cnt[@]}

for e in ${!cnt[@]}
do
    if [ ${cnt[e]} -eq "1" ]; then
        echo "$e"
        break
    fi
done