Download - Bài tập shell_full

Transcript
Page 1: Bài tập shell_full

1

BÀI TẬP SHELL CƠ BẢN

Bài 1 /try_var.sh#!/bin/shsalutation="Hello"echo $salutationecho "The program $0 is now running"echo "The second parameter was $2"echo "The first parameter was $1"echo "The parameter list was $*"echo "The user's home directory is $HOME"echo "Please enter a new greeting"read salutationecho $salutationecho "The script is now complete"exit 0=======Bài 2 :/variable.sh#!/bin/shmyvar="Hi there"echo $myvarecho "message : $myvar"echo 'message : $myvar'echo "message :\$myvar"echo Enter some textread myvarecho '$myvar' now equals $myvarexit 0========

Page 2: Bài tập shell_full

2

Bài 3/and.sh#!/bin/shtouch file_onerm -f file_twoif [ -f file_one ] && echo "hello" && [ -f file_two ] && echo "there"then echo -e "in if"else echo -e "in else"fiexit 0=========Bài 4 : /for.sh#!/bin/shrm -rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4for file in fred*do if [ -d "$file" ]; then break; fidoneecho first directory fred was $file

Page 3: Bài tập shell_full

3

exit 0

======Bài 5 : case1.sh#!/bin/shecho "Is it morning? Please answer yes or no"read timeofdaycase "$timeofday" in "yes") echo "Good Morning";; "no" ) echo "Good Afternoon";; "y" ) echo "Good Morning";; "n" ) echo "Good Afternoon";; * ) echo "Sorry, answer not recognised";;esacexit 0=======Bài 6 : case2.sh#!/bin/shecho "Is it morning? Please answer yes or no"read timeofdaycase "$timeofday" in "yes" | "y" | "Yes" | "YES" ) echo "Good Morning";; "n*" | "N*" ) echo "Good Afternoon";;

Page 4: Bài tập shell_full

4

* ) echo "Sorry, answer not recognised";;esacexit 0========

Bài 7 : case3.sh#!/bin/shecho "Is it morning? Please answer yes or no"read timeofdaycase "$timeofday" in "yes" | "y" | "Yes" | "YES" ) echo "Good Morning" echo "Up bright and early this morning?" ;; "[nN]*" ) echo "Good Afternoon" ;; * ) echo "Sorry, answer not recognised" echo "Please answer yes or no" exit 1 ;;esacexit 0

Page 5: Bài tập shell_full

5

=======

Bài 8 /cat_here.sh#! /bin/shcat > test.txt <<!YOURLABEL!HelloThis ishere document!YOURLABEL!======

Bài 9 /chess_board.sh#!/bin/shfor (( i = 1; i <= 9; i++ )) ### Outer for loop ###do for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ### do tot=`expr $i + $j` tmp=`expr $tot % 2` if [ $tmp -eq 0 ]; then echo -e -n "\033[47m " else echo -e -n "\033[40m " fi done

Page 6: Bài tập shell_full

6

echo -e -n "\033[33m" #### set back background colour to black echo "" #### print the new line ###done========

Bài 10/ccal.sh#! /bin/sh# Hilight current day in cal - alot smaller than gcal ;)_TODAY=`date +%e`_B=`tput smso`_N=`tput rmso`echocal |sed s/"$_TODAY"/"$_B$_TODAY$_N"/=======

Bài 11/colon.sh#!/bin/shrm -f fredif [ -f fred ]; then :else echo file fred does not existfiexit 0======

Page 7: Bài tập shell_full

7

Bài 12/continue.sh#!/bin/shrm -rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4for file in fred*do if [ -d "$file" ]; then continue fi echo file is $filedoneexit 0=======

Bài 13/dot_coma.sh#!/bin/shecho "Inside script"PATH=/mypath/bin: /usr/localecho $PATHecho "Script end"=======

Bài 14/elseif_contr.sh#!/bin/sh

Page 8: Bài tập shell_full

8

echo -n "Is it morning? Please answer yes or no: "read timeofdayif [ "$timeofday" = "yes" ]; then echo "Good morning"elif [ "$timeofday" = "no" ]; then echo "Good afternoon"else echo "Sorry, $timeofday not recognized. Enter yes or no" exit 1fiexit 0 ========

Bài 15/evaluate.sh#!/bin/shx=0while [ "$x" -ne 10 ] ; do echo $x x=$(($x + 1))doneexit 0========

Bài 16/exec_demo.sh#! /bin/shecho "Try to execute mc program"

Page 9: Bài tập shell_full

9

exec mcecho "you can not see this message !"========

Bài 17 /exec_demo.sh#! /bin/shecho "Try to execute mc program"exec mcecho "you can not see this message !"=====

Bài 18/export1.sh#!/bin/shfoo="This is foo"export bar="This is bar"=======

Bài 19/export2.sh#!/bin/sh

echo "Value: $foo"echo "Value: $bar"./export2.shexport1.sh#!/bin/shfoo="Thí is foo"export bar="This is bar"

Page 10: Bài tập shell_full

10

./export1.shvalue:Value : This is bar========

Bài 20/findit.sh#! /bin/sh# findit.sh -- simple search script by Luke - 07Feb2005#_findit() {

find . -name "*$_expr*"}echo "Enter search pattern: \c"read _exprif [ "$_expr" = "" ]; then echo "Do you REALLY want to list ALL the files? [y/n] \c" read _list if [ "$_list" = y ]; then _findit else exit fifi_findit========

Page 11: Bài tập shell_full

11

Bài 21 /for1.sh#!/bin/bashecho "Can you see the following:"for (( i=1; i<=5; i++ ))do for (( j=1; j<=i; j++ )) do echo -n "$i" done echo ""done========

Bài22 /for2.sh#!/bin/bashecho "Can you see the following:"for (( i=1; i<=5; i++ ))do for (( j=1; j<=i; j++ )) do echo -n "$j" done echo ""done========

Bài 23/for3.sh

Page 12: Bài tập shell_full

12

#!/bin/bashecho "Can you see the following:"for (( i=1; i<=5; i++ ))do for (( j=1; j<=i; j++ )) do echo -n "$j" done echo ""done=======

Bài 22/for4.sh#!/bin/bash

echo "Climb the steps of success"

for (( i=1; i<=5; i++ ))do for (( j=1; j<=i; j++ )) do echo -n " |" done echo "_ "done========

Page 13: Bài tập shell_full

13

Bài 23/for5.sh#!/bin/bash#star

echo "Stars"for (( i=1; i<=5; i++ ))do for (( j=1; j<=i; j++ )) do echo -n " *" done echo ""done=========

Bài 24/for6.sh#!/bin/bashecho "Stars"for (( i=1; i<=5; i++ ))do for (( j=1; j<=i; j++ )) do echo -n " *" done echo ""donefor (( i=5; i>=1; i-- ))

Page 14: Bài tập shell_full

14

do for (( j=1; j<=i; j++ )) do echo -n " *" done echo ""done==========

Bài 25/for7.sh#!/bin/bashclearfor (( i=1; i<=3; i++ ))do for (( j=1; j<=i; j++ )) do echo -n "|Linux" done echo "______"donefor (( i=3; i>=1; i-- ))do for (( j=1; j<=i; j++ )) do echo -n "|Linux" done if [ $i -eq 3 ]; then

Page 15: Bài tập shell_full

15

echo -n "______" echo -n -e ">> Powerd Server.\n" else echo "~~~~~" fidone=========

Bài 26/for_loop2.sh#!/bin/shfor file in $(ls f*.sh); do lpr $filedone=======

Bài 27/for_loop.sh#!/bin/shfor foo in bar fud 13do echo $foodoneexit 0=======

Bài 28/function.sh#!/bin/shsample_text="global variable"

Page 16: Bài tập shell_full

16

foo() { local sample_text="local variable" echo "Function foo is executing" echo $sample_text}echo "script starting"echo $sample_textfooecho "script ended"echo $sample_textexit 0=========

Bài 29/get_name.sh#!/bin/shyes_or_no() { echo "In function parameters are $*" echo "Param 1 $1 and Param2 $2" while true do echo -n "Enter yes or no" read x case "$x" in y | yes ) return 0;; n | no ) return 1;; * ) echo "Answer yes or no" esac

Page 17: Bài tập shell_full

17

done}echo "Original parameters are $*"if yes_or_no "Is your name” “ $1?" then echo "Hi $1"elif echo "Never mind"fiexit 0======

Bài 30/gifto_jpg.sh#!/bin/shfor image in *.gifdo cjpeg $image >${image%%gif}jpgdone=======

Bài 32/if_control.sh#!/bin/shecho "Is it morning? Please answer yes or no"read timeofdayif [ $timeofday = "yes" ]; then echo "Good morning"

Page 18: Bài tập shell_full

18

else echo "Good afternoon"fiexit 0==========

Bài 31/max_numbers.sh- Tìm sô lon nhat trong dãy so nhâp vào- Dao nguoc 1 dãy so. Ví du: 1 2 3 4 dao nguoc lai: 4 3 2 1#!/bin/bash# input an array of elementsecho -n "n= "read nfor ((i=0; i<n; i++))doecho -n "a[$i] " =read a[$i]done

#max of an arraymax=${a[0]}echo "max1 = $max"for ((i=1; i<n; i++))do if [ "${a[$i]}" -gt "$max" ]; thenmax=${a[$i]}

Page 19: Bài tập shell_full

19

fidoneecho "max = $max"exit $?

=====================#!/bin/bash# input an array of elementsfunction input(){echo -n "n= "read nfor ((i=0; i<n; i++))doecho -n "a[$i] " =read a[$i]done}#max of two numbersfunction max2nums(){if [ "$1" -gt "$2" ]; thenmax1=$1echo $1elsemax1=$2echo $2

Page 20: Bài tập shell_full

20

fireturn $max1}#max of an arrayfunction maxs(){max=${a[0]}for ((i=1; i<n; i++))do max=$(max2nums ${a[$i]} $max)doneecho "max = $max"}inputmaxsexit $?========

Bài 32/menu.sh#!/bin/bash#Tao menu tương tac vơí ngươì dùng.#!/bin/bashwhile :doclearecho "---------------------------------------"echo " Main Menu"

Page 21: Bài tập shell_full

21

echo "---------------------------------------"echo "[1] Show today date/time"echo "[2] Show all files in current directory"echo "[3] Show calendar"echo "[4] Exit/Stop"echo "======================="echo -n "Enter your choice [1-4]: "read choicecase $choice in1) echo "Today is `date` "echo "Press Enter key to continue ..."; read;;2) echo "Files in $PWD"; ls -lecho "Press Enter key to continue..."; read;;3) cal ; echo "Press Enter key to continue..."; read;;4) exit 0;;*) echo "Please choice 1,2,3,4. Press Enter key to continue..."; read;;esacdone=======

Bài 33/my_function.sh#!/bin/shfoo() { echo "Function foo is executing"

Page 22: Bài tập shell_full

22

}echo "script starting"fooecho "script ended"exit 0=========

Bài 34/or_list.sh#!/bin/shrm -f file_oneif [ -f file_one ] || echo "hello" || echo "there"then echo "in if"else echo "in else"fiexit 0=======

Bài 35/param_exp.sh#!/bin/shunset fooecho ${foo:-bar} foo=fudecho ${foo:-bar}foo=/usr/bin/X11/startx

Page 23: Bài tập shell_full

23

echo ${foo#*/}echo ${foo##*/}bar=/usr/local/etc/local/networksecho ${bar%local*}echo ${bar%%local*}exit 0========

Bài 36/passwd.sh#!/bin/shecho "Enter password"read trythiswhile [ "$trythis" != "secret" ]; do echo "Sorry, try again" read trythisdoneexit 0========

Bài 37/passwd1.sh#!/bin/shecho "TAO MAT KHAU "echo " Nhap mat khau "read passw >> /dev/nullecho " Xac nhan mat khau "read passw1 echo " Passw co" ${#passw} "ky tu"

Page 24: Bài tập shell_full

24

while [ "$passw" != "$passw1" ] && echo " Mat khau sai" || [ ${#passw} -le 6 ] && echo "Mat khau can dai hon 6 ky tu" || [ "$passw" = "" ] && echo " Mat khau khong duoc la rong"do read passwecho "Xac nhan "read passw1doneecho " Mat khau OK!"exit 0=======

Bài 38/Viêt chuong trinh shell giai phuong trinh bâc hai : ax2 + bx +c =0 voi cac tham sô a,b,c nhâp tu ban phim va cac kêt qua chinh xac dên hai chu sô.#!/bin/bashecho -n "a= "read aecho -n "b= "read becho -n "c= "read cdelta=$(echo "$b^2 - 4*$a*$c" | bc)if [ $delta -lt 0 ]then

Page 25: Bài tập shell_full

25

echo "pt vo nghiem"elif [ "$delta" -eq 0 ]thenecho -n "pt co nghiem kep x= "x=$(echo "scale=2; -$b/(2*$a)" | bc)echo "$x"elseecho "phuong trinh co 2 nghiem"x1=$(echo "scale=2; -($b + sqrt($delta))/(2*$a)" | bc)echo "x1= $x1"x2=$(echo "scale=2; -($b - sqrt($delta))/(2*$a)" | bc)echo "x2= $x2"fiexit 0=======

Bài 39/reverse.sh<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><META http-equiv=Content-Type content="text/html; charset=windows-1252"></HEAD><BODY><PRE>#!/bin/bash#

Page 26: Bài tập shell_full

26

# Linux Shell Scripting Tutorial 1.05r3, Summer-2002## Written by Vivek G. Gite &lt;[email protected]&gt;## Latest version can be found at http://www.nixcraft.com/## Script to reverse given no## Algo:# 1) Input number n# 2) Set rev=0, sd=0# 3) Find single digit in sd as n % 10 it will give (left most digit)# 4) Construct revrse no as rev * 10 + sd# 5) Decrment n by 1# 6) Is n is greater than zero, if yes goto step 3, otherwise next step# 7) Print revif [ $# -ne 1 ]then echo "Usage: $0 number" echo " I will find reverse of given number"

Page 27: Bài tập shell_full

27

echo " For eg. $0 123, I will print 321" exit 1fi

n=$1rev=0sd=0while [ $n -gt 0 ]do sd=`expr $n % 10` rev=`expr $rev \* 10 + $sd` n=`expr $n / 10`done echo "Reverse number is $rev"# ./ch.sh: vivek-tech.com to nixcraft.com referance converted using this tool# See the tool at http://www.nixcraft.com/uniqlinuxfeatures/tools/#</PRE></BODY></HTML>==========

Bài40/set_use.sh#!bin/shecho Current date is $(date)set $(date)

Page 28: Bài tập shell_full

28

echo The month is $2echo The year is $6exit 0=========

Bài 41/test_exist.sh#!/bin/shif [ -f .profile ] ; then exit 0fiexit 1=====

Bài 42/until_user.sh#!/bin/shecho "Locate for user ..."until who | grep "$1" > /dev/nulldo sleep 60doneecho -e \\aecho "***** $1 has just logged in *****"exit 0======

Bài 43/use_command.sh#!/bin/shecho Current directory is $PWDecho It contents $(ls –a) filesexit 0

Page 29: Bài tập shell_full

29

========

Bài 44/use_trap.sh#!/bin/shtrap 'rm -f /tmp/my_tmp_file_$$' INTecho creating file /tmp/my_tmp_file_$$date > /tmp/my_tmp_file_$$echo "Press interrupt (Ctrl-C) to interrupt...."while [ -f /tmp/my_tmp_file_$$ ]; do echo File exists sleep 1doneecho The file no longer existstrap -INTecho creating file /tmp/my_tmp_file_$$date > /tmp/my_tmp_file_$$echo "Press interrupt (Ctrl-C) to interrupt...."while [ -f /tmp/my_tmp_file_$$ ]; do echo File exists sleep 1doneecho We never get hereexit 0=======

Bài 45/user_ID.sh#! /bin/bash echo -n "User id: " read uid

Page 30: Bài tập shell_full

30

temp=`grep "[^:]* :$uid" /etc/passwd` temp2=${temp#*x:} if [ "${temp2%%:*}" = "$uid" ] then echo User name: ${temp%%:*} ush=${temp##*:} temp=${temp%:*} echo Home Folder: ${temp##*:} echo User shell: $ush

temp=${temp#* :$uid:} echo GUID: ${temp%%:*} else echo "User id is not exist!" fi

========Bài 46 /using_shift#!/bin/shwhile [ "$1" != "" ]; do echo "$1" shiftdoneexit 0=========Bài 47/while_for.sh#!/bin/shfoo=1while [ "$foo" -le 16 ]do echo "Here $foo"

Page 31: Bài tập shell_full

31

foo=$(($foo+1))doneexit 0==========

Bài 48/string.sh#!/bin/bashstring=abcDefghu1234EDstuVecho ${#string} #19echo `expr length $string` #19echo `expr index "$string" c ` #3echo `expr index "$string" E ` #9echo ${string:2} # cDefghEDstuVFecho ${string: -3} # tuV#echo ${string 7 4}echo `expr substr $string 3 5 ` # cDefgecho ${string#a*u} # 1234EDstuVecho ${string#*123} #4EDstuVecho ${string##a*u} # Vecho ${string%s*V} #abcDefghu1234EDecho ${string%234*V} #abcDefghu1echo ${string%%u*V} #abcDefghecho ${string/abc/xyz} #xyzDefghu1234EDstuVread Necho `expr substr $string 3 $N `========Bài 49 /array.sharray[xx]# Khai báo mảng ,Co thê khai báo mảng băng lênh declare –a array ${array[xx]} #Lây giá tri mảng ${array[@]} hoăc ${array[*]} # lây tâtv cả

Page 32: Bài tập shell_full

32

phân tư cua mảng${#array[@]} hoăcz ${#array[*]} # tông sô phân tư cua mảngunset array[1] # xoá phân tư thư 2 cua mảng arrayunset array # xoa toan bô mảngarray[5]=`expr ${array[11]} + ${array[13]}`array=( zero one two three four )-> array[0]=zero ; array[4]=fourarray=( [xx]=XXX [yy]=YYY ...)array=([17]=seventeen [21]=twenty-one)array=( zero one two three four five )echo ${array[0]} # zeroecho ${array:0} # zeroecho ${array:1} # ero : lây tư vi trí sô 1 cuả phân tư thư v nhâtecho ${#array[0]} # 4 : chiêu daì cuả phần tư thư nhâtecho ${#array} # 4echo ${#array[1]} # 3 : chiêu daì cuả phần tư thư 2echo ${#array[*]} # 6 : sô phần tư cua mảngecho ${#array[@]} # 6 : sô phân tư cua mảng.array2=( [0]="first element" [1]="second element" [3]="fourth element" )echo ${array2[0]} # first elementecho ${array2[1]} # second elementecho ${array2[2]} # không khơi tao nên co giá tri nullecho ${array2[3]} # fourth elementarrayZ=( one two three four five five )

Page 33: Bài tập shell_full

33

echo ${arrayZ[@]:0} # one two three four five five : tât cả cac phân tưecho ${arrayZ[@]:1} # two three four five five : lây tư phân tư thư 1

echo ${arrayZ[@] 2} # two three : lây phân tư 1 đên 2#Ví du : khai báo mảng rôngarray0=( first second third )array1=( ' ' ) # "array1" co 1 phần tư rông.array2=( ) # mảng rông#Ví du : nơí rông mang ( khai bao thêm phân tư vào mảng )array0=( "${array0[@]}" "new1" ) # ${array0[@]} là toan bômang cu, new1 là phần tư mơiarray1=( "${array1[@]}" "new1" )array2=( "${array2[@]}" "new1" )#hoăcarray0[${#array0[*]}]="new2"array1[${#array1[*]}]="new2"array2[${#array2[*]}]="new2"#Ví du : chep mảngarray2=( "${array1[@]}" )#hoăcarray2="${array1[@]}" Bai 50 string_proccess.sh

Nhập danh sách tên file tư dong lênh, VD: tuan.txt tuan.sh tuananh.txt tuan.Trong đo phần tư cuôi cùng là thư

Page 34: Bài tập shell_full

34

muc.Loc ra các file là *.txt và ghi các file đo vào thư muc trên(vi du trên là thư muc /home) Trong bài giải co xư ly tên file băng phương pháp xư ly xâu như sau:Môt biên VALUE="string.txt"ta co dùng lênh : " ${VALUE##*.txt}" thì no sẽ cắt VALUE tư điêm đầu đên vi trí co xuât hiên xâu ".txt" Tưc là nêu echo ${VALUE##*.txt}cho kêt quả là xâu rông .Vơi VALUE="tuan.txt51pm1" kêt quả là: 51pm1 và biên VALUE bi cắt mât chuôi tuan.txt

d=” “while [ “$1” != “ ” ]doif [ “${$1##*.txt}” = “ ” ]thend=”$d $1”elsethumuc=“$1”fishiftdoneif [ -e “$thumuc” ]thenok=”true”elsemkdir “$thumuc”fi

Page 35: Bài tập shell_full

35

set $decho “$d”while [ “$1” ! = “ ” ]doif [ -e “$1” ] thenmv “ $1” “ $thumuc”elsevi “$thumuc”fishiftdone

====================================