[Bash] 分支、循環、數組

分支api

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

數組的下標和數組的值:找出一個不配對的數組元素bash

#!/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
相關文章
相關標籤/搜索