03 tk2123 - pemrograman shell-2
TRANSCRIPT
TK2123 Pemrograman ShellSemester Genap 2015/2016
TASS, Bandung 2016
www.tass.telkomuniversity.ac.id
Hanya dipergunakan untuk kepentingan pengajaran di lingkungan Telkom Applied Science School (TASS)
Dasar Pemrograman Shell
Kondisi / PencabanganPerulanganBerhenti / keluar blok kendali
Struktur Kendali
Alternatif proses yang akan dieksekusi berdasar nilai kebenaran kondisi.
Operai logika : AND, OR, NOT
Kondisi
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
Sintaks
#!/bin/bash if [ "$#" -gt 0 ] then echo "There's Beans" fi if [ "$1" = "cool" ] then echo "Cool Beans" fi
nano latihan3a.sh
#!/bin/bash
if [ "$1" = "cool" ]
then
echo "Cool Beans"
else
echo "Not Cool Beans"
fi
nano latihan3b.sh
#!/bin/bash
if [ "$1" = "cool" ] then
echo "Cool Beans"
elif [ "$1" = "neat" ] then
echo "Neat cool"
else
echo "Not Cool Beans“
fi
nano latihan3c.sh
#!/bin/bash
if [ "$1" = "cool" ]
then
echo "Cool Beans"
else
echo "Not Cool Beans"
fi
nano latihan3d.sh
#!/bin/bash
if [ -f "$1" ] then
echo "$1 is a file"
else
echo "$1 is not a file"
fi
nano latihan3e.sh
Operasi
#!/bin/bash a=10 b=20
if [ $a == $b ] then echo "a is equal to b" elif [ $a -gt $b ] then echo "a is greater than b" elif [ $a -lt $b ] then echo "a is less than b" else echo "None of the condition met" fi
nano latihan3f.sh
$ true$ echo $?#Hasilnya ?$ false$ echo $?#Hasilnya ?
True and or False
$ if true; then echo "It's true."; fi#Hasilnya ?$ if false; then echo "It's false."; fi#Hasilnya ?
Banyak dipakai dengan perintah if untuk membuat keputusan benar/salah. Jika ekspresi bernilai benar, test keluar dengan status 0, sebaliknya berstatus 1
Bentuk sintaksnya :# Pertamatest expression
# Kedua[ expression ]
Test
Ekspresi
#!/bin/bash
if [ -f .bash_profile ];then
echo "You have a .bash_profile"
else
echo "You have no .bash_profile!"
fi
nano latihan3g.sh
#!/bin/bash
if test $1 -gt 0then echo "$1 number is positive"fi
nano latihan3h.sh
Merupakan perintah yang dipakai untuk mengakhiri skrip dan menset status exitnya.
Contoh #Keluar skrip dengan exit status 0 (success)exit 0
#Keluar skrip dengan exit status 1 (failure)exit 1
Exit
$ id -u501$ suPassword:# id -u0
ID super user
#!/bin/bash
if [ $(id -u) = "0" ]; then echo "superuser"fi
nano latihan3i.sh
#!/bin/bash
if [ $(id -u) != "0" ]; then
echo “Harus superuser untuk menjalankan skrip ini"
exit 1
fi
nano latihan3j.sh
#!/bin/bashif [ $# -eq 0 ] then echo "$0 : Ketikkkan angka integer" exit 1fiif test $1 -gt 0 then echo "$1 bilangan positif"else echo "$1 bilangan negatif"fi
nano latihan3k.sh
Case – 1 (multiple if dengan variabel tunggal)
case $variable in match_1)
commands_to_execute_for_1 ;;
match_2) commands_to_execute_for_2 ;; match_3) commands_to_execute_for_3 ;; . . . *) (Optional - any other value) commands_to_execute_for_no_match ;; esac
case $variable-name in pattern1|pattern2|pattern3) command1 ... commandn;; pattern4|pattern5|pattern6) command1 ... commandn;; pattern7|pattern8|patternN) command1 ... commandN;; *) esac
Case – 2 (multiple if dengan variabel tunggal)
#!/bin/bash
case $( arch ) in # "arch" arsitektur mesin
# Equivalent to 'uname -m' ...
i386 ) echo "80386-based machine";;
i486 ) echo "80486-based machine";;
i586 ) echo "Pentium-based machine";;
i686 ) echo "Pentium2+-based machine";;
* ) echo "Other type of machine";;
esac
nano latihan3l.sh
#!/bin/bash
option="${1}" case ${option} in -f) FILE="${2}" echo "File name is $FILE" ;; -d) DIR="${2}" echo "Dir name is $DIR" ;; *) echo "`basename ${0}`:usage: [-f file] | [-d directory]" exit 1 # Command to come out of the program with status 1 ;; esac
nano latihan3m.sh
#!/bin/bashNOW=$(date +"%a")case $NOW inMon)echo "Full backup";;Tue|Wed|Thu|Fri)echo "Partial backup";;Sat|Sun)echo "No backup";;*) ;;esac
nano latihan3n.sh
#!/bin/bash
# Skrip backup mysql, webserver & file-file ke tape
opt=$1
case $opt in
sql)
echo "Running mysql backup using mysqldump tool..." ;;
sync)
echo "Running backup using rsync tool..." ;;
tar)
echo "Running tape backup using tar tool..." ;;
*)
echo "Backup shell script utility"
echo "Usage: $0 {sql|sync|tar}"
echo "sql : Run mySQL backup utility."
echo "sync : Run web server backup utility."
echo "tar : Run tape backup utility." ;;
esac
nano latihan3o.sh
#!/bin/bashecho -n "Do you agree with this? [yes or no]: "read ynocase $yno in [yY] | [yY][Ee][Ss] ) echo "Agreed" ;; [nN] | [n|N][O|o] ) echo "Not agreed, can't proceed the installation"; exit 1 ;; *) echo "Invalid input" ;;esac
nano latihan3p.sh
#!/bin/bashcase "$1" in 'start') echo "Starting application" /usr/bin/startpc ;; 'stop') echo "Stopping application" /usr/bin/stoppc ;; 'restart') echo "Usage: $0 [start|stop]" ;;esac
nano latihan3q.sh
!/bin/bash
# Testing ranges of characters.
echo; echo "Hit a key, then hit return."
read Keypress
case "$Keypress" in
[[:lower:]] ) echo "Lowercase letter";;
[[:upper:]] ) echo "Uppercase letter";;
[0-9] ) echo "Digit";;
* ) echo "Punctuation, whitespace, or other";;
esac
# range karakter [square brackets],
# range POSIX [[double square brackets]]
nano latihan3r.sh
Merupakan struktur kendali yang memungkinkan perulangan tertentu terhadap proses.
Yang harus diperhatikan :Kondisi berhenti harus tercapai jika tidak maka akan terjadi ENDLESS LOOP (hang)
Perulangan (LOOPING)
while [ condition ]do
command1command2commandN
done
Macam perulangan - 1
for { variable name } in { list } do command1 command2 … commandN done
Macam perulangan - 2
for (( expr1; expr2; expr3 )) do command1 command2 … commandN done
until [ condition ]do
command1command2commandN
done
Macam perulangan - 3
#!/bin/bashc=1while [ $c -le 5 ]doecho "Welcome $c times"(( c++ ))
done
nano latihan3s.sh
#!/bin/bash
for i in 1 2 3 4 5doecho "Welcome $i times"done
nano latihan3t.sh
#!/bin/bash
for (( i = 0 ; i <= 5; i++ ))do echo "Welcome $i times"done
nano latihan3u.sh
#!/bin/bash
i=1;for (( ; ; ))do sleep $i echo "Number: $((i++))"done
nano latihan3v.sh
#!/bin/bash
i=1for day in Mon Tue Wed Thu Frido echo "Weekday $((i++)) : $day"done
nano latihan3w.sh
#!/bin/bash
i=1for day in "Mon Tue Wed Thu Fri"do echo "Weekday $((i++)) : $day"done
nano latihan3x.sh
#!/bin/bash
i=1weekdays="Mon Tue Wed Thu Fri"for day in $weekdaysdo echo "Weekday $((i++)) : $day"done
nano latihan3y.sh
#!/bin/bash
for (( i=1; i <= 5; i++ ))do echo "Random number $i: $RANDOM"done
nano latihan3z0.sh
#!/bin/bash
for ((i=1, j=10; i <= 5 ; i++, j=j+5))do echo "Number $i: $j"done
nano latihan3z1.sh
#!/bin/bashpilih=until [ "$pilih" = "0" ]; do echo "" echo "PROGRAM MENU" echo "1 - display free disk space" echo "2 - display free memory" echo "" echo "0 - exit program" echo "" echo -n "Enter selection: " read pilih echo "" case $pilih in 1 ) df ;; 2 ) free ;; 0 ) echo “Tekan satu key. . ." ; read -n 1; exit ;; * ) echo “Ketikkan 1, 2, atau 0" esacdone
nano latihan3z2.sh
echo -e : enable interpretation of backslash escapes
tput : menggerakkan kursor di layar
Warna dan kursor
Warna
#!/bin/bashfor x in 0 1 4 5 7 8 ; do for i in `seq 30 37`; do for a in `seq 40 47`; do echo -ne "\e[$x;$i;$a""m\\\e[$x;$i;$a""m\e[0;37;40m"
done echo; done doneecho " ";
nano tabwarna.sh
$ PS1="\[\033[0;32;40m\u@\h:\w\$ \]”
$ PS1="\[\033[0;37;44m\u@\033[0;32;43m\h:\033[0;33;41m\w$\033[0m\]“
$ PS1="\[\033[1;34;40m[\033[1;31;40m\u@\h:\w\033[1;34;40m]\033[1;37;40m $\033[0;37;0m\] "
Latihan
#!/bin/bashfor (( i = 1; i <= 9; i++ )) do for (( j = 1 ; j <= 9; j++ )) do tot=`expr $i + $j` tmp=`expr $tot % 2` if [ $tmp -eq 0 ]; then echo -e -n "\033[47m “ #putih else echo -e -n "\033[40m “ #Hitam fi done echo -e -n "\033[40m" #black echo ""done
nano latihan3z3.sh
- Memindahkan posisi kursor ke baris L kolom C : \033[<L>;<C>H atau \033[<L>;<C>f- Memindahkan kursor ke atas N baris : \033[<N>A- Memindahkan kursor ke bawah N baris : \033[<N>B- Memindahkan kursor maju N kolom : \033[<N>C- Memindahkan kursor mundur N kolom : \033[<N>D- Hapus layar, kursor ke (0,0) #sudut kiri atas \033[2J- Hapus sampai akhir baris : \033[K- Simpan posisi kursor : \033[s- Restore posisi kursor : \033[u
Kursor
$ tput cup 2 3$ tput clear$ tput cols$ tput lines$ tput -S <<END >clear > cup 2 4 > END$ tput setb 4$ tput setf 4$ tput bold$ tput sgr0$ echo `tput bold`guide`tput sgr0`$ tput smul$ tput rmul$ echo `tput smul`guide`tput rmul`$ tput civis$ tput cnorm
Latihan
#!/bin/bashclearfor (( i=1; i <= 5; i++ ));do for (( j=1; j <= 100; j++ ));do acakx=$(( RANDOM%20+5 )) acaky=$(( RANDOM%70+10 )) acakw=$(( RANDOM%8+1 )) tput cup $acakx $acaky echo -en "\033[1;3${acakw};4${acakw}m*" sleep 0.05 done doneecho -en "\033[0m"
nano blinkindark.sh
#!/bin/bashfor a in 0 1 4 5 7; do echo "a=$a " for (( f=0; f<=9; f++ )) ; do for (( b=0; b <=9; b++ )) ; do echo -ne "\\033[${a};3${f};4${b}m" echo -ne "\\033[${a};3${f};4${b}m" echo -ne "\\033[0m " done echo done echo doneecho
nano tabelwarna.sh
#!/bin/bashclearfor ((i=1;i<= 8; i++)) do for ((j=1;j<= 8; j++)) do total=$(($i+$j)) tmp=$(($total%2)) if [ $tmp -eq 0 ] then echo -e -n "\033[47m $j " #ke samping else echo -e -n "\033[40m $j " #ke samping sleep 0.1 fi done echo "" #ke bawah doneecho -e -n "\033[0m"
nano chessboard.sh
#!/bin/bashtput cleartput cup 3 15tput setaf 3echo "XYX Appl. V.1"tput sgr0 tput cup 5 17# Set reverse video modetput revecho "M A I N - M E N U"tput sgr0 tput cup 7 15echo "1. User Management"tput cup 8 15echo "2. Service Management"tput cup 9 15echo "3. Process Management"tput cup 10 15echo "4. Backup"tput boldtput cup 12 15read -p "Enter your choice [1-4] " choice
tput cleartput sgr0tput rc
nano menutput.sh
#!/bin/bashecho -en "\033[0m"clearwarna=( 41 43 45 44 46 47 42 )for (( i=0; i <= 6; i++ )) do tput cup 10 0 for (( j=1; j <= 20;j++ )) #ke kanan do echo -en "\033[${warna[i]}m " sleep 0.03 done for (( j=10; j <= 20; j++ )) #ke bawah do tput cup $j 20 echo -en "\033[s" echo -e "\033[${warna[i]}m " done for (( j=20; j >= 1; j-- )) #ke kiri do tput cup 20 $j echo -en "\033[s" echo -en "\033[${warna[i]}m " sleep 0.03 done for (( j=20; j >= 12; j-- )) #ke atas do tput cup $j 0 echo -en "\033[s" echo -en "\033[${warna[i]}m " sleep 0.03 done doneecho -en "\033[0m"
nano onyamuk.sh