10. The case statement example
#!/bin/bash
echo -e "Enter some character : \c"
#\c是末尾不加换行符号;#-e表示激活转义字符。使用-e选项时,将\c特别加以处理,而不会将它当成一般文字输出;
read value
case $value in
[a-z] )
echo "User entered $value a to z" ;;
[A-Z] )
echo "User entered $value A to Z" ;;
#如果运行输入大写字母输出的仍然是上一行的语句,则在终端先执行命令LANG=C
[0-9] )
echo "User entered $value 0 to 9" ;;
? )
echo "User entered $value special character" ;;
#包括任何其他特殊符号比如^&%...
* )
echo "Unknown input" ;;
esac
11. Array variables
#!/bin/bash
os=('ubuntu' 'windows' 'kali')
os[3]='mac' #add new element 'mac'
#os[0]='mac' #replace 'ubuntu' by 'mac'
unset os[2] #remove 'kali'
echo "${os[@]}" #print all
echo "${os[1]}" #print the second element
echo "${!os[@]}" #print all index values
echo "${#os[@]}" #print the total number of elements
string=sadfadfadfag
echo "${string[@]}"
echo "${string[0]}"
echo "${string[1]}"
echo "${#string[@]}"
12. While loops
#!/bin/bash
#while loops
n=1
#while [ $n -le 10 ]
while (( $n <= 10 ))
#note the difference of brackets and expression
do
echo "$n"
#n=$((n+1))
#((n++))
(( ++n ))
#three expressions are all right
done
13. Using sleep and open terminal with While loop
#!/bin/bash
#while loops
n=1
while [ $n -le 10 ]
do
echo "$n"
((n++))
sleep 1
#print $n every one second
done
#!/bin/bash
#while loops
n=1
while [ $n -le 3 ]
do
echo "$n"
((n++))
#gnome-terminal & #two methods to open 3 terminals
xterm &
done
14. Read a file content in bash
#!/bin/bash
#while loops
while read p
do
echo $p
done < hello.sh
cat hello.sh | while read p
do
echo $p
done
#while IFS= read -r line
while IFS=' ' read -r line
do
echo $line
done < /etc/host.conf
15. Until loops
#!/bin/bash
# until loops
n=1
until [ $n -ge 10 ]
#until (( $n -gt 10 ))
do
echo $n
n=$(( n+1 ))
done
16. For loops
#!/bin/bash
# for loops
for i in 1 2 3 4 5
do
echo $i
done
for i in {1..10}
do
echo $i
done
echo ${BASH_VERSION}
for i in {0..10..2} #{start..end..increment} can use above bash version 4.0
do
echo $i
done
for ((i=0; i<5; i++))
do
echo $i
done
17. Use FOR loop to execute command
#!/bin/bash
# for loops
for command in ls pwd date
do
echo "----------$command----------"
$command #execute command
done
for item in *
do
if [ -d $item ]
#if [ -f $item ]
then
echo $item
fi
done
18. Select loop
#!/bin/bash
# select loop
select name in mark john tom ben
do
case $name in
mark)
echo mark selected
;;
john)
echo john selected
;;
tom)
echo tom selected
;;
ben)
echo ben selected
;;
*)
echo "Error please provide the no. between 1..4"
esac
done
#the same results:
select name in mark john tom ben
do
echo "$name selected"
done
19. Break and continue
#!/bin/bash
for (( i=1; i<=10; i++ ))
do
if [ $i -gt 5 ]
then
break
fi
echo "$i"
done
for (( i=1; i<=10; i++ ))
do
if [ $i -eq 3 -o $i -eq 6 ]
then
continue
fi
echo "$i"
done
以上内容参考bilibili站视频https://www.bilibili.com/video/av51517726
/*今日标签*/
我终将青春还给了他
连同指尖弹出的盛夏