Showing posts with label Shell. Show all posts

Whiptail - Công cụ tạo giao diện đồ họa trên terminal (bash shell)

Công cụ này được dùng để tạo ra một giao diện đồ họa đơn giản để install hoặc settting một phần mềm nào đó trên môi trường bash shell của terminal.

Một ví dụ, chẳng hạn khi muốn config cấu hình của raspberry pi:
Gõ lệnh "sudo raspi-config" 

sẽ ra giao diện như dưới đây :


Note: Chi tiết cách sử dụng có thể tham khảo wiki





Tuesday, December 31, 2019

Arithmetic Expansion


Gán kết quả của một phép toán cho biến, có hai cách thực hiện:
 var=`expr statement`  
 var=$((statement))  

Ex:
 #!/bin/sh  
   
 x=10  
   
 val=`expr $x + 2`  
 echo "Total value : $val"  
   
 val2=$(( $x + 5))  
 echo "Total value : $val2"  

 $ ./test.sh  
 Total value : 12  
 Total value : 15  
   

Monday, July 13, 2015
Tag :

Command Execution


Có hai cách để thực hiện command execution trong shell:
Syntax:
 `command`  
   
 or  
 $(command)  

Ex:
 #!/bin/sh  
 echo The current directory is `pwd`  
 echo The current users are $(who)  
 exit 0  

Shell - Command build-in the shell


Shell cung cấp sẵn rất nhiều command hữu ích, dưới đây sẽ liệt kê một số cmd hay dùng.

1. set /unset
Lệnh set truyền giá trị cho các special variables (parameter variables) từ $1, $2, ...
Lệnh unset sẽ remove một biến khỏi môi trường shell.

Ex:
set
 $ set foo bar  
 $ echo $1  
 foo  
 $ echo $2  
 bar  
 $ echo $*  
 foo bar  
   

unset
 #!/bin/sh  
 foo="Hello World"   
 echo $foo  
 unset foo  
 echo $foo  

2. eval
Lệnh eval cho phép lấy được giá trị cuối cùng của một biến trong trường hợp biến đó được gán theo kiểu bắc cầu.

Ex:
 #!/bin/sh  
   
 foo=10  
 x=foo  
 y='$'$x
 eval z='$'$x
 echo $y  
 echo $z

 $./test.sh  
 $foo       # y value
 10         # z value

3. exec
Lệnh exec có hai cách dùng:
+ Thay thế shell hiện tai bằng một chương trình khác
Ex:
 $ exec wall "Thanks for all the fish"  
Shell hiện tại sẽ kết thúc và thay thế bằng chương trình wall.

+ Chỉnh sửa file descriptor hiện tại, trường hợp này ít được dùng
Ex:
 exec 3< afile  
File descriptor 3 sẽ được mở để đọc dữ liệu từ afile.

4. exit n
Trả về mã code của một chương trình shell khi nó kết thúc.

Exit Code Description
126 The file was not executable
127 A command was not found
128 and above A signal occurred

Giá trị exit 0 thường được dùng để biểu diễn cho việc trả về mã code thành công, và exit 1 là có lỗi xảy ra.

Ex:
 #!/bin/sh  
 if [ -f .profile ]; then  
 exit 0  
 fi  
 exit 1  

5. export
Lệnh export dùng để tạo ta một biến môi trường - environment variables, nhờ đó biến đó có thể được truy cập từ một chương trình hoặc shell script khác.

Ex:
 #!/bin/sh  
 echo $MYNAME  
 echo $YOURNAME  

 $MYNAME=Obama  
 $YOURNAME=Putin  
 $./test.sh  
   
 Putin

6. expr
expr được dùng trong việc mở rộng các phép toán số học trong shell. Xem lại Arithmetic Expansion.

7. printf
Hiển thị thông tin ra màn hình.
 printf "format string" parameter1 parameter2 ...  
format string rất đơn giản, nó tương tự như trong C/C++, chỉ có một điểm khác đó là không print được số float bởi vì các phép toán trong shell chỉ thực hiện với số int.


Escape Sequence Description
\" Double quote
\\ Backslash character
\a Alert (ring the bell or beep)
\b Backspace character
\c Suppress further output
\f Form feed character
\n Newline character
\r Carriage return
\t Tab character
\v Vertical tab character
\ooo The single character with octal value ooo
\xHH The single character with the hexadecimal value HH


Conversion Specifier Description
D Output a decimal number.
C Output a character.
S Output a string.
% Output the % character.

Ex:
 $ printf "%s\n" hello  
 hello  
 $ printf "%s %d\t%s" "Hi There" 15 people  
 Hi There 15  
 people  

8. return
return dùng khi muốn trở về từ một function, thường là return n, với n là mã code trả về.

9. shift
Lệnh shift dịch chuyển giá trị của các parameter variables trong lần lượt sang trái.

Ex:
 #!/bin/sh  
   
 echo "===== before shift ======"  
 echo "\$1=$1"  
 echo "\$2=$2"  
 echo "\$3=$3"  
   
 echo "===== affter shift ======"  
 shift  
 echo "\$1=$1"  
 echo "\$2=$2"  
 echo "\$3=$3"  
   

 $ ./helloworld.sh foo bar zar  
 ===== before shift ======  
 $1=foo  
 $2=bar  
 $3=zar  
 ===== affter shift ======  
 $1=bar  
 $2=zar  
 $3=  
   

10. find
Tìm kiếm trong thư mục.

Ex: Tìm kiếm file trong thư mục
Syntax:
find <dir> -name <filename>

11. grep
Tìm kiếm một mẫu.

Ex: Tìm kiếm device file mà tên của nó có chuỗi ký tự fb.
 $ ls /dev/ | grep "fb"  
 fb0  
   

12. man
Show ra documents của một command.
Syntax:
 $ man <command name)   

Ex: Document của lệnh ls.
 $ man ls  


Sunday, July 12, 2015
Tag :

Shell - Lists



1. The AND List
AND list cho phép bạn thực hiện một chuỗi liên tục các câu lệnh, muốn lệnh tiếp theo được chạy thì tất cả các lệnh trước đó phải thực hiện thành công.

Syntax:
 statement1 && statement2 && statement3 && ...  

Ex:
 #!/bin/sh  
 touch file_one  
 rm -f file_two  
 if [ -f file_one ] && echo "hello" && [ -f file_two ] && echo " there"  
 then  
 echo "in if"  
 else  
 echo "in else"  
 fi  
 exit 0  

 $./test.sh  
 hello  
 in else  

2. The OR List
OR list cho phép bạn thực hiện một chuỗi các câu lệnh cho đến khi nào có một câu lệnh thực hiện thành công, khi đó sẽ dừng lại, không thực hiện thêm bất cứ câu lệnh nào nữa.

Syntax:
 statement1 || statement2 || statement3 || ...  

Ex:
 #!/bin/sh  
 rm -f file_one  
 if [ -f file_one ] || echo "hello" || echo " there"  
 then  
   echo "in if"  
 else  
   echo "in else"  
 fi  
 exit 0  

 $./test.sh  
 hello  
 in if  


Shell - IO Redirections and Pipes


Theo mặc định của shell, khi thực hiện một command thì nó sẽ lấy dữ liệu đầu vào (nếu có) từ standard input (stdin) và xuất kết quả ra standard output (stdout). Tuy nhiên shell cũng cung cấp cú pháp để có thể thay thế stdin và stdout bằng đối tượng khác đó chính là file.


1. Output Redirection
Syntax:
 $ command > filename   
Xuất kết quả và ghi vào filename (nếu filename chưa có thì tạo mới)

 $ command >> filename  
Tương tự như trên, nhưng ghi tiếp (append) vào filename nếu filename đã tồn tại và có nội dung khác trước đó.

Ex:
 [ninhld@localhost ex]$ date > time.txt  
 [ninhld@localhost ex]$ cat time.txt   
 Sun Jul 12 21:46:04 ICT 2015  
 [ninhld@localhost ex]$   
 [ninhld@localhost ex]$   
 [ninhld@localhost ex]$ uptime >> time.txt   
 [ninhld@localhost ex]$ cat time.txt   
 Sun Jul 12 21:46:04 ICT 2015  
 21:46:24 up 3:03, 3 users, load average: 0.38, 0.56, 0.64  
   

2. Input Redirection
Syntax:
 $ command < filename   
Ngược lại với Output Redirection.

Ex:
 [ninhld@localhost ex]$ more < time.txt   
 Sun Jul 12 21:46:04 ICT 2015  
 21:46:24 up 3:03, 3 users, load average: 0.38, 0.56, 0.64  

3. Discard the output
Khi không muốn xuất kết quả hoặc các thông báo lỗi ra màn hình, shell cung cấp cú pháp để loại bỏ các kết quả và thông báo lỗi như sau.

Syntax:
 $ command > /dev/null         #Discard stdout   
 $ command > /dev/null 2>&1    #Discard stdout and stderr  
Trong đó /dev/null là một device file đặc biệt, tất cả các luồng dữ liệu đi vào nó đều được loại bỏ.

Ex:
 $ date > /dev/null  
 $ date > /dev/null 2>&1  
Bạn sẽ không có gì được print trên terminal.

4. Redirection Commands
Bảng dưới đây liệt kê tất cả các cú pháp redirection commands, bao gồm các cúa pháp đã liệt kê ở các mục trên.


Command Description
pgm > file Output of pgm is redirected to file
pgm < file Program pgm reads its input from file.
pgm >> file Output of pgm is appended to file.
n > file Output from stream with descriptor n redirected to file.
n >> file Output from stream with descriptor n appended to file.
n >& m Merge output from stream n with stream m.
n <& m Merge input from stream n with stream m.
<< tag Standard input comes from here through next tag at start of line.
| Takes output from one program, or process, and sends it to another.

5. Pipes
Pipes là đường ống dùng để truyền kết quả từ đầu ra của một lệnh vào đầu vào của một lệnh khác được thực hiện sau. Ký hiệu của pipe là dấu gạch đứng.

Ex:
 $ ls /dev | grep "fb"  
 fb0  

Lệnh ls /dev liệt kê ra danh sách tất cả các device file nằm trong thư mục /dev, kết quả này lại là đầu vào của lệnh grep (lệnh tìm kiếm theo mẫu) thông qua pipe, kết quả của chuỗi lệnh trên là lọc ra được "fb0" tương ứng với /dev/fb0.


Shell - Quoting Mechanisms



1. Cặp dấu nháy đơn
Chuỗi ký tự nằm giữa hai dấu nháy đơn sẽ được hiểu theo đúng nghĩa "đen" của nó, ký tự $ bị vô hiệu hóa, tất cả mọi thứ trong cặp dấu nháy đơn sẽ được giữ y nguyên khi echo ra.

Ex:
 [ninhld@localhost ex]$ NAME=obama  
 [ninhld@localhost ex]$ echo $NAME  
 obama  
 [ninhld@localhost ex]$ echo '$NAME'  
 $NAME  

2. Cặp dấu nháy kép
Cách sử dụng của dấu nháy kép cũng giống như dấu nháy đơn ngoại trừ một điểm là dấu nháy kép không thoát khỏi ý nghĩa đặc biệt của ký tự $. Điều đó có nghĩa là ta có thể đưa giá trị một biến vào trong một chuỗi.

Ex:
 [ninhld@localhost ex]$ NAME=obama  
 [ninhld@localhost ex]$ echo "Barack $NAME"  
 Barack obama  
   

3. Ký tự chéo ngược
Ký tự chéo ngược (backslash) đi trước một ký tự đặc biệt sẽ làm thoát khỏi ý nghĩa đặc biệt của ký tự đó.

Ex:
 [ninhld@localhost ex]$ NAME=obama  
 [ninhld@localhost ex]$ echo "Barack \$NAME"  
 Barack $NAME  

4. Ký tự nháy ngược
Ký tự nháy ngược hay dấu huyền ( ` command`) là một ký tự đặc biệt trong shell. Chuỗi ký tự nằm giữa hai dấu nháy ngược sẽ được xem là một câu lệnh, được thực hiện và giá trị trả về sẽ được lưu vào biến.

Ex:
 [ninhld@localhost ex]$ DATE=`date`  
 [ninhld@localhost ex]$ echo $DATE  
 Sun Jul 12 16:47:04 ICT 2015  
   


Shell - Shell Substitutions


1. Command Substitution
Syntax:
 `command`  

Ex:
 #!/bin/sh  
   
 DATE=`date`  
 echo "Date is $DATE"  
   
 USERS=`who | wc -l`  
 echo "Logged in user are $USERS"  
   
 UP=`date ; uptime`  
 echo "Uptime is $UP"  

 $./test.sh  
 Date is Thu Jul 2 03:59:57 MST 2009  
 Logged in user are 1  
 Uptime is Thu Jul 2 03:59:57 MST 2009  
 03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15  

2. Variable Substitution
Form Description
${var} Substitue the value of var.
${var:-word} If var is null or unset, word is substituted for var. The value ofvar does not change.
${var:=word} If var is null or unset, var is set to the value of word.
${var:?message} If var is null or unset, message is printed to standard error. This checks that variables are set correctly.
${var:+word} If var is set, word is substituted for var. The value of var does not change.

Ex:
 #!/bin/sh  
   
 echo ${var:-"Variable is not set"}  
 echo "1 - Value of var is ${var}"  
   
 echo ${var:="Variable is not set"}  
 echo "2 - Value of var is ${var}"  
   
 unset var  
 echo ${var:+"This is default value"}  
 echo "3 - Value of var is $var"  
   
 var="Prefix"  
 echo ${var:+"This is default value"}  
 echo "4 - Value of var is $var"  
   
 echo ${var:?"Print this message"}  
 echo "5 - Value of var is ${var}"  

 $./test.sh  
 Variable is not set  
 1 - Value of var is  
 Variable is not set  
 2 - Value of var is Variable is not set  
   
 3 - Value of var is  
 This is default value  
 4 - Value of var is Prefix  
 Prefix  
 5 - Value of var is Prefix  

Shell - Shell Functions


1. Creating Functions
Syntax:
 function_name () {   
   list of commands  
 }  

Ex:
 #!/bin/sh  
   
 # Define your function here  
 Hello () {  
   echo "Hello World"  
 }  
   
 # Invoke your function  
 Hello  

 $./test.sh  
 Hello World  

2. Pass Parameters to a Function
Việc pass parameters vào một function tương tự như đối với khi pass vào shell script.

Ex:
 #!/bin/sh  
   
 # Define your function here  
 Hello () {  
   echo "Hello World $1 $2"  
 }  
   
 # Invoke your function  
 Hello Zara Ali  

 $./test.sh  
 Hello World Zara Ali  

3. Returning Values from Functions
Syntax:
 function_name () {    
   list of commands   
   return code  
  }   

Ex:
 #!/bin/sh  
   
 # Define your function here  
 Hello () {  
   echo "Hello World $1 $2"  
   return 10  
 }  
   
 # Invoke your function  
 Hello Zara Ali  
   
 # Capture value returnd by last command  
 ret=$?  
   
 echo "Return value is $ret"  

 $./test.sh  
 Hello World Zara Ali  
 Return value is 10  

4. Nested Functions
Việc trong một hàm lại gọi một hàm con nữa cũng tương tự như trong lập trình C.

Ex:
 #!/bin/sh  
   
 # Calling one function from another  
 number_one () {  
   echo "This is the first function speaking..."  
   number_two  
 }  
   
 number_two () {  
   echo "This is now the second function speaking..."  
 }  
   
 # Calling function one.  
 number_one  

 $./test.sh  
 This is the first function speaking...  
 This is now the second function speaking...  

5. Function Call from Promp
Syntax:
 $. test.sh  
Với test.sh là shell script có chứa function.

Ex:
 $. test.sh  
 This is the first function speaking...  
 This is now the second function speaking...  
 $   
 $ number_one   
 This is the first function speaking...  
 This is now the second function speaking...  
   

Khi muốn loại bỏ function:
Syntax:
 $unset .f function_name  

Shell - Loop Control

The infinite Loop (Vòng lặp không xác định)
Là vòng lặp mà điều kiện - condition của vòng lặp luôn đúng, dẫn đến việc không bào giờ thoát ra khỏi vòng lặp, muốn nó thoát ra được vòng lặp thì shell cũng cung cấp hai Loop Control tương tự như trong C là break và continue.

Ex (infinite loop):
 #!/bin/sh  
   
 a=10  
   
 while [ $a -ge 10 ]  # a >= 10
 do  
   echo $a  
   a=`expr $a + 1`    # a = a + 1
 done  

1. The break statement
Syntax:
 break  
or
 break n  
Với n là vòng lặp lồng nhau thứ n.

Ex1 (break):
 #!/bin/sh  
   
 a=0  
   
 while [ $a -lt 10 ]  
 do  
   echo $a  
   if [ $a -eq 5 ]  
   then  
    break  
   fi  
   a=`expr $a + 1`  
 done  

 $./test.sh  
 0  
 1  
 2  
 3  
 4  
 5  

Ex1 (break n):
 #!/bin/sh  
   
 for var1 in 1 2 3  
 do  
   for var2 in 0 5  
   do  
    if [ $var1 -eq 2 -a $var2 -eq 0 ]  
    then  
      break 2  
    else  
      echo "$var1 $var2"  
    fi  
   done  
 done  

 $./test.sh  
 1 0  
 1 5  

2. The continue statement
Syntax:
 continue  
or
 continue n  
Với n là vòng lặp lồng nhau thứ n.

Ex:
 #!/bin/sh  
   
 NUMS="1 2 3 4 5 6 7"  
   
 for NUM in $NUMS  
 do  
   Q=`expr $NUM % 2`  
   if [ $Q -eq 0 ]  
   then  
    echo "Number is an even number!!"  
    continue  
   fi  
   echo "Found odd number"  
 done  

 $./test.sh  
 Found odd number  
 Number is an even number!!  
 Found odd number  
 Number is an even number!!  
 Found odd number  
 Number is an even number!!  
 Found odd number  


Shell - Shell Loops


1. Shell Loop
1.1 The while loop
Syntax:
 while condition  
 do  
   Statement(s) to be executed if condition is true  
 done  
or
 while condition; do  
   Statement(s) to be executed if condition is true  
 done  

Ex:
 #!/bin/sh  
   
 a=0  
   
 while [ $a -lt 10 ]  
 do  
   echo $a  
   a=`expr $a + 1`  
 done  

 $./test.sh  
 0  
 1  
 2  
 3  
 4  
 5  
 6  
 7  
 8  
 9  

1.2 The for loop
Syntax:
 for var in word1 word2 ... wordN  
 do  
   Statement(s) to be executed for every word.  
 done  
Trong đó var là biến thay đổi, nó sẽ lần lượt được gán các giá trị từ word1 -> wordN.

Ex1:
 #!/bin/sh  
   
 for var in 0 1 2 3 4 5 6 7 8 9  
 do  
   echo $var  
 done  

 $./test.sh  
 0  
 1  
 2  
 3  
 4  
 5  
 6  
 7  
 8  
 9  

Ex2:
 #!/bin/sh  
   
 for FILE in $HOME/.bash*  
 do  
   echo $FILE  
 done  

 $./test.sh  
 /root/.bash_history  
 /root/.bash_logout  
 /root/.bash_profile  
 /root/.bashrc  

1.3 The until loop
Syntax:
 until condition  
 do  
   Statement(s) to be executed until condition is true  
 done  


 #!/bin/sh  
   
 a=0  
   
 until [ ! $a -lt 10 ]  
 do  
   echo $a  
   a=`expr $a + 1`  
 done  

 $./test.sh  
 0  
 1  
 2  
 3  
 4  
 5  
 6  
 7  
 8  
 9  

1.4 The select loop
Syntax:
 select var in word1 word2 ... wordN  
 do  
   Statement(s) to be executed for every word.  
 done  

Ex:
 #!/bin/ksh  
   
 select DRINK in tea cofee water juice appe all none  
 do  
   case $DRINK in  
    tea|cofee|water|all)   
      echo "Go to canteen"  
      ;;  
    juice|appe)  
      echo "Available at home"  
    ;;  
    none)   
      break   
    ;;  
    *) echo "ERROR: Invalid selection"   
    ;;  
   esac  
 done  

 $./test.sh  
 1) tea  
 2) cofee  
 3) water  
 4) juice  
 5) appe  
 6) all  
 7) none  
 #? juice  
 Available at home  
 #? none  
 $  

2. Nesting Loops (Vòng lặp lồng nhau)
Syntax:
 while condition1 ; # this is loop1, the outer loop  
 do  
   Statement(s) to be executed if condition1 is true  
   
   while condition2 ; # this is loop2, the inner loop  
   do  
    Statement(s) to be executed if condition2 is true  
   done  
   
   Statement(s) to be executed if condition1 is true  
 done  

Ex:
 #!/bin/sh  
   
 a=0  
 while [ "$a" -lt 10 ]  # this is loop1  
 do  
   b="$a"  
   while [ "$b" -ge 0 ] # this is loop2  
   do  
    echo -n "$b "  
    b=`expr $b - 1`  
   done  
   echo  
   a=`expr $a + 1`  
 done  

 $./test.sh  
 0  
 1 0  
 2 1 0  
 3 2 1 0  
 4 3 2 1 0  
 5 4 3 2 1 0  
 6 5 4 3 2 1 0  
 7 6 5 4 3 2 1 0  
 8 7 6 5 4 3 2 1 0  
 9 8 7 6 5 4 3 2 1 0  

Shell - Decision Making


1. The if...else statements
1.1 if...fi statement
Syntax:
 if [ expression ]  
 then  
   Statement(s) to be executed if expression is true  
 fi  
or
 if [ expression ]; then  
   Statement(s) to be executed if expression is true   
 fi  

Ex:
 #!/bin/sh  
   
 a=10  
 b=20  
   
 if [ $a == $b ]  
 then  
   echo "a is equal to b"  
 fi  
   
 if [ $a != $b ]  
 then  
   echo "a is not equal to b"  
 fi  

 $./test.sh  
 a is not equal to b  

1.2 if...else...fi statement
Syntax:
 if [ expression ]  
 then  
   Statement(s) to be executed if expression is true  
 else  
   Statement(s) to be executed if expression is not true  
 fi  

Ex:
 #!/bin/sh  
   
 a=10  
 b=20  
   
 if [ $a == $b ]  
 then  
   echo "a is equal to b"  
 else  
   echo "a is not equal to b"  
 fi  

 $./test.sh  
 a is not equal to b  

1.3 if...elif...else...fi statement
Syntax:
 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  

Ex:
 #!/bin/sh  
   
 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  

 $./test.sh  
 a is less than b  

2. The case...esac Statement
Syntax:
 case word in  
  pattern1)  
    Statement(s) to be executed if pattern1 matches  
    ;;  
  pattern2)  
    Statement(s) to be executed if pattern2 matches  
    ;;  
  pattern3)  
    Statement(s) to be executed if pattern3 matches  
    ;;  
 esac  

Ex1:
 #!/bin/sh  
   
 FRUIT="kiwi"  
   
 case "$FRUIT" in  
   "apple") echo "Apple pie is quite tasty."   
   ;;  
   "banana") echo "I like banana nut bread."   
   ;;  
   "kiwi") echo "New Zealand is famous for kiwi."   
   ;;  
 esac  

 $./test.sh  
 New Zealand is famous for kiwi.  

Ex2:
 #!/bin/sh  
 echo "Is it morning? Please answer yes or no"  
 read timeofday  
 case "$timeofday" in  
 yes | y | Yes | YES )  
      echo "Good Morning"  
      echo "Up bright and early this morning"  
      ;;  
 [nN]*)  
      echo "Good Afternoon"  
      ;;  
 *)  
      echo "Sorry, answer not recognized"  
      echo "Please answer yes or no"  
      exit 1  
      ;;  
 esac  
 exit 0  

Saturday, July 11, 2015
Tag :

Shell - Basic Operators


1 Toán tử số học (Arithmetic Operators)
Giả sử có hai biến có giá trị như sau:
 a=10  
 b=20  


Operator Description Example
+ Addition - Adds values on either side of the operator `expr $a + $b` will give 30
- Subtraction - Subtracts right hand operand from left hand operand `expr $a - $b` will give -10
* Multiplication - Multiplies values on either side of the operator `expr $a \* $b` will give 200
/ Division - Divides left hand operand by right hand operand `expr $b / $a` will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder `expr $b % $a` will give 0
= Assignment - Assign right operand in left operand a=$b would assign value of b into a
== Equality - Compares two numbers, if both are same then returns true. [ $a == $b ] would return false.
!= Not Equality - Compares two numbers, if both are different then returns true. [ $a != $b ] would return true.

 #!/bin/sh  
 a=10  
 b=20  
 val=`expr $a + $b`  
 echo "a + b : $val"  
   
 val=`expr $a - $b`  
 echo "a - b : $val"  
   
 val=`expr $a \* $b`  
 echo "a * b : $val"  
   
 val=`expr $b / $a`  
 echo "b / a : $val"  
   
 val=`expr $b % $a`  
 echo "b % a : $val"  
   
 if [ $a == $b ]  
 then  
   echo "a is equal to b"  
 fi  
   
 if [ $a != $b ]  
 then  
   echo "a is not equal to b"  
 fi  

 $ ./test.sh  
 a + b : 30  
 a - b : -10  
 a * b : 200  
 b / a : 2  
 b % a : 0  
 a is not equal to b  
   

2 Toán tử quan hệ (Relational
 Operators)
Giả sử có hai biến có các giá trị như sau:
 a=10  
 b=20  


Operator Description Example
-eq Checks if the value of two operands are equal or not, if yes then condition becomes true. [ $a -eq $b ] is not true.
-ne Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. [ $a -ne $b ] is true.
-gt Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. [ $a -gt $b ] is not true.
-lt Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. [ $a -lt $b ] is true.
-ge Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. [ $a -ge $b ] is not true.
-le Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. [ $a -le $b ] is true.

Ex:
 #!/bin/sh  
 a=10  
 b=20  
   
 if [ $a -eq $b ]  
 then  
   echo "$a -eq $b : a is equal to b"  
 else  
   echo "$a -eq $b: a is not equal to b"  
 fi  
   
 if [ $a -ne $b ]  
 then  
   echo "$a -ne $b: a is not equal to b"  
 else  
   echo "$a -ne $b : a is equal to b"  
 fi  
   
 if [ $a -gt $b ]  
 then  
   echo "$a -gt $b: a is greater than b"  
 else  
   echo "$a -gt $b: a is not greater than b"  
 fi  
   
 if [ $a -lt $b ]  
 then  
   echo "$a -lt $b: a is less than b"  
 else  
   echo "$a -lt $b: a is not less than b"  
 fi  
   
 if [ $a -ge $b ]  
 then  
   echo "$a -ge $b: a is greater or equal to b"  
 else  
   echo "$a -ge $b: a is not greater or equal to b"  
 fi  
   
 if [ $a -le $b ]  
 then  
   echo "$a -le $b: a is less or equal to b"  
 else  
   echo "$a -le $b: a is not less or equal to b"  
 fi  
   

 $ ./test.sh   
 10 -eq 20: a is not equal to b  
 10 -ne 20: a is not equal to b  
 10 -gt 20: a is not greater than b  
 10 -lt 20: a is less than b  
 10 -ge 20: a is not greater or equal to b  
 10 -le 20: a is less or equal to b  
   

3 Toán tử  logic (Boolean Operators)
Giả sử có hai biến có các giá trị như sau:
 a=10  
 b=20  


Operator Description Example
! This is logical negation. This inverts a true condition into false and vice versa. [ ! false ] is true.
-o This is logical OR. If one of the operands is true then condition would be true. [ $a -lt 20 -o $b -gt 100 ] is true.
-a This is logical AND. If both the operands are true then condition would be true otherwise it would be false. [ $a -lt 20 -a $b -gt 100 ] is false.

Ex:
 #!/bin/sh  
   
 a=10  
 b=20  
   
 if [ $a != $b ]  
 then  
   echo "$a != $b : a is not equal to b"  
 else  
   echo "$a != $b: a is equal to b"  
 fi  
   
 if [ $a -lt 100 -a $b -gt 15 ]  
 then  
   echo "$a -lt 100 -a $b -gt 15 : returns true"  
 else  
   echo "$a -lt 100 -a $b -gt 15 : returns false"  
 fi  
   
 if [ $a -lt 100 -o $b -gt 100 ]  
 then  
   echo "$a -lt 100 -o $b -gt 100 : returns true"  
 else  
   echo "$a -lt 100 -o $b -gt 100 : returns false"  
 fi  
   
 if [ $a -lt 5 -o $b -gt 100 ]  
 then  
   echo "$a -lt 100 -o $b -gt 100 : returns true"  
 else  
   echo "$a -lt 100 -o $b -gt 100 : returns false"  
 fi  

 $./test.sh  
 10 != 20 : a is not equal to b  
 10 -lt 100 -a 20 -gt 15 : returns true  
 10 -lt 100 -o 20 -gt 100 : returns true  
 10 -lt 5 -o 20 -gt 100 : returns false  

4 Toán tử chuỗi (String Operators)
Toán tử chuỗi dùng để so sánh hai chuỗi ký tự.

Giả sử có hai biến chứa các chuối như sau:
 a="abc"  
 b="efg"  


Operator Description Example
= Checks if the value of two operands are equal or not, if yes then condition becomes true. [ $a = $b ] is not true.
!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. [ $a != $b ] is true.
-z Checks if the given string operand size is zero. If it is zero length then it returns true. [ -z $a ] is not true.
-n Checks if the given string operand size is non-zero. If it is non-zero length then it returns true. [ -z $a ] is not false.
str Check if str is not the empty string. If it is empty then it returns false. [ $a ] is not false.

Ex:
 #!/bin/sh  
 a="abc"  
 b="efg"  
   
 if [ $a = $b ]  
 then  
   echo "$a = $b : a is equal to b"  
 else  
   echo "$a = $b: a is not equal to b"  
 fi  
   
 if [ $a != $b ]  
 then  
   echo "$a != $b : a is not equal to b"  
 else  
   echo "$a != $b: a is equal to b"  
 fi  
   
 if [ -z $a ]  
 then  
   echo "-z $a : string length is zero"  
 else  
   echo "-z $a : string length is not zero"  
 fi  
   
 if [ -n $a ]  
 then  
   echo "-n $a : string length is not zero"  
 else  
   echo "-n $a : string length is zero"  
 fi  
   
 if [ $a ]  
 then  
   echo "$a : string is not empty"  
 else  
   echo "$a : string is empty"  
 fi  
   

 $ ./test.sh   
 abc = efg: a is not equal to b  
 abc != efg : a is not equal to b  
 -z abc : string length is not zero  
 -n abc : string length is not zero  
 abc : string is not empty  
   

5 Toán tử tệp (File Operators)
Toán tử tệp dùng để kiểm tra các thuộc tính của tệp.


Operator Description Example
-b file Checks if file is a block special file if yes then condition becomes true.
-c file Checks if file is a character special file if yes then condition becomes true.
-d file Check if file is a directory if yes then condition becomes true.
-f file Check if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true.
-g file Checks if file has its set group ID (SGID) bit set if yes then condition becomes true.
-k file Checks if file has its sticky bit set if yes then condition becomes true.
-p file Checks if file is a named pipe if yes then condition becomes true.
-t file Checks if file descriptor is open and associated with a terminal if yes then condition becomes true.
-u file Checks if file has its set user id (SUID) bit set if yes then condition becomes true.
-r file Checks if file is readable if yes then condition becomes true.
-w file Check if file is writable if yes then condition becomes true.
-x file Check if file is execute if yes then condition becomes true.
-s file Check if file has size greater than 0 if yes then condition becomes true.
-e file Check if file exists. Is true even if file is a directory but exists.

Ex:
 #!/bin/sh  
   
 file="/usr/bin/sh"  
   
 if [ -r $file ]  
 then  
   echo "File has read access"  
 else  
   echo "File does not have read access"  
 fi  
   
 if [ -w $file ]  
 then  
   echo "File has write permission"  
 else  
   echo "File does not have write permission"  
 fi  
   
 if [ -x $file ]  
 then  
   echo "File has execute permission"  
 else  
   echo "File does not have execute permission"  
 fi  
   
 if [ -f $file ]  
 then  
   echo "File is an ordinary file"  
 else  
   echo "This is sepcial file"  
 fi  
   
 if [ -d $file ]  
 then  
   echo "File is a directory"  
 else  
   echo "This is not a directory"  
 fi  
   
 if [ -s $file ]  
 then  
   echo "File size is zero"  
 else  
   echo "File size is not zero"  
 fi  
   
 if [ -e $file ]  
 then  
   echo "File exists"  
 else  
   echo "File does not exist"  
 fi  
   

 $ ./test.sh   
 File has read access  
 File does not have write permission  
 File has execute permission  
 File is an ordinary file  
 This is not a directory  
 File size is zero  
 File exists  
   


Shell - Test and [ ] Expression


Lệnh test dùng để đánh giá một biểu thức điều kiện. Người ta thường sử dụng lệnh này để đánh giá một điều kiện trong một mệnh đề điều kiện ( if ) hoặc trong một mệnh đề vòng lặp ( while ). Cú pháp của lệnh test như sau:

 test expression  
 hoặc:  
 [expression]  

Trong đó expression là biểu thức điều kiện cần được đánh giá.
Lệnh test và [ ] thường được dùng với một số toán tử đã được xây dựng sẵn trong shell.
Sau khi thực hiện, lệnh test sẽ trả về giá trị logic là Đúng (True) hoặc Sai (False).

Ex:
test.sh
 #!/bin/sh  
   
 echo "Do you love me ?"  
 read result  
   
 if test "$result" = "yes"  
 then  
      echo "I'm very happy ^_^"  
 else  
      echo "I'm so sad"  
 fi  
   
 echo "Do you like me ?"  
 read result  
 if [ "$result" = "yes" ]  
 then  
      echo "I'm very happy ^_^"  
 else  
      echo "I'm so sad"  
 fi  
   

 $ ./test.sh   
 Do you love me ?  
 yes  
 I'm very happy ^_^  
 Do you like me ?  
 no  
 I'm so sad  
   

Shell - Using Arrays

1. Defining Array Values

 array_name[index]=value  

nếu dùng bash shell thì có thêm cách sau:
 array_name=(value1 ... valuen)  

Ex:
 NAME[0]="Zara"  
 NAME[1]="Qadir"  
 NAME[2]="Mahnaz"  
 NAME[3]="Ayan"  
 NAME[4]="Daisy"  

hoặc
 NAME=(Zara Qadir Mahnaz Ayan Daisy)  

2. Accessing Array Values
2.1 Truy cập từng phần tử trong mảng
 ${array_name[index]}  

Ex:
test.sh
 #!/bin/sh  
   
 NAME[0]="Zara"  
 NAME[1]="Qadir"  
 NAME[2]="Mahnaz"  
 NAME[3]="Ayan"  
 NAME[4]="Daisy"  
 echo "First Index: ${NAME[0]}"  
 echo "Second Index: ${NAME[1]}"  

 $./test.sh  
 First Index: Zara  
 Second Index: Qadir  

2.2 Truy cập tất cả các phần tử trong mảng

 ${array_name[*]}  
 ${array_name[@]}  

Ex:
test.sh
 #!/bin/sh  
   
 NAME[0]="Zara"  
 NAME[1]="Qadir"  
 NAME[2]="Mahnaz"  
 NAME[3]="Ayan"  
 NAME[4]="Daisy"  
 echo "First Method: ${NAME[*]}"  
 echo "Second Method: ${NAME[@]}"  

 $./test.sh  
 First Method: Zara Qadir Mahnaz Ayan Daisy  
 Second Method: Zara Qadir Mahnaz Ayan Daisy  

Shell - Special Variables


Bảng dưới đây liệt kê các biến đặc biệt của shell, hay còn gọi là parameter variables, là các đối số được dùng trong shell script.


Variable Description
$0 The filename of the current script.
$n These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).
$# The number of arguments supplied to a script.
$* All the arguments are double quoted ( $1 $2 ...). If a script receives two arguments, $* is equivalent to $1 $2.
$@ All the arguments are individually double quoted ( "$1" "$2" ...). If a script receives two arguments, $@ is equivalent to $1 $2.
$? The exit status of the last command executed.
$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
$! The process number of the last background command.


1. Command-Line Arguments
test.sh
 #!/bin/sh  
   
 echo "File Name: $0"  
 echo "First Parameter : $1"  
 echo "First Parameter : $2"  
 echo "Quoted Values: $@"  
 echo "Quoted Values: $*"  
 echo "Total Number of Parameters : $#"  

 $./test.sh Zara Ali  
 File Name : ./test.sh  
 First Parameter : Zara  
 Second Parameter : Ali  
 Quoted Values: Zara Ali  
 Quoted Values: Zara Ali  
 Total Number of Parameters : 2  

2. Special Parameters $* and $@
$* và $@ đều liệt kê ra danh sách biến nhưng theo những cách khác nhau và phụ thuộc vào biến môi trường IFS.

 $ IFS=‘’ 
 $ set foo bar bam  
 $ echo "$@"  
 foo bar bam  
 $ echo "$*"  
 foobarbam  
 $ unset IFS  
 $ echo "$*"  
 foo bar bam  

3. Exit Status
$? cho biết giá trị trả về của lệnh cuối cùng.

 $./test.sh Zara Ali  
 File Name : ./test.sh  
 First Parameter : Zara  
 Second Parameter : Ali  
 Quoted Values: Zara Ali  
 Quoted Values: Zara Ali  
 Total Number of Parameters : 2  
 $echo $?  
 0  
 $  

Vậy lệnh cuối cùng
 echo "Total Number of Parameters : $#"  
trả về exit code là 0.


Shell - Using Variables


1. Variable Names
Tên của biến có thể bao gồm các ký tự chữ ( a to z or A to Z), số ( 0 to 9) hoặc ký tự gạch dưới ( _ ).
Không được dùng các ký tự đặc biệt như  !,*, hoặc - , bởi vì chúng có ý nghĩa đặc biệt trong shell

Ex: biến hợp lệ
 _ALI  
 TOKEN_A  
 VAR_1  
 VAR_2 
 var_3 

Ex: biến không hợp lệ
 2_VAR  
 -VARIABLE  
 VAR1-VAR2  
 VAR_A!  

2. Defining Variables
Biến được định nghĩa / khai báo như sau:
 variable_name=variable_value  

Ex:
 name=Obama  
 full_name="Barack Obama"  #dung với dấu nháy kép nếu là chuỗi ký tự
 age=54   

3. Accessing Values
Để truy cập giá trị được lưu trữ trong biến, dùng tiền tố dollar ( $ ) trước biến.

 #!/bin/sh  
   
 NAME="Zara Ali"  
 echo $NAME  

 $./test.sh  
 Zara Ali  


4. Read-only Variables
Read-only chỉ cho phép biến được gán giá trị một lần duy nhất:
 #!/bin/sh  
   
 NAME="Zara Ali"  
 readonly NAME  
 NAME="Qadiri"  

 $./test.sh  
 /bin/sh: NAME: This variable is read only.  

5. Unsetting Variables
Unsetting hoặc deleting một biến có nghĩa là xóa biến đó khỏi danh sách các biến được theo dõi của shell, không thể truy cập giá trị của biến được nữa.
Cú pháp:
 unset variable_name  

Ex:
 #!/bin/sh  
   
 NAME="Zara Ali"  
 unset NAME  
 echo $NAME  

6. Variable Types
Shell cũng có các loại biến khác nhau được liệt kê dưới đây:
+ Local Variables
Là biến chỉ hoạt động trong nhữ cảnh hiện tại trong shell (shell pronpt), nó không thể được truy cập từ những chương trình khác được bắt đầu bởi shell.

test.sh
 #!/bin/sh   
 echo $NAME  

 $NAME=obama  
 $echo $NAME  
 obama  
 $./test.sh     #test.sh là một chương trình khác được start bởi shell hiện tại và nó không thể truy cập được giá trị của biến NAME
   

+ Environment Variables
Biến môi trường cho phép tất cả các chương trình được truy cập giá trị của nó. Biến môi trường có thể là mặc định của shell hoặc do người dùng tự định nghĩa.


Lệnh env show ra các biến môi trường của shell và các application đã installed:
 $ env  
 XDG_VTNR=1  
 MATE_DESKTOP_SESSION_ID=this-is-deprecated  
 SSH_AGENT_PID=1426  
 XDG_SESSION_ID=1  
 HOSTNAME=localhost.localdomain  
 XDG_GREETER_DATA_DIR=/var/lib/lightdm-data/ninhld  
 IMSETTINGS_INTEGRATE_DESKTOP=yes  
 GPG_AGENT_INFO=/home/ninhld/.cache/keyring-rp2hZY/gpg:0:1  
 TERM=xterm-256color  
 SHELL=/bin/bash  
 ...  

Lệnh export để định nghĩa biến môi trường:
 $export NAME=obama   
 $./test.sh  
 obama  

+ Shell Variables
Shell variables là biến đặc biệt được định nghĩa bởi shell, một số trong chúng là environment variables và một số là local variables. Shell variables được chỉ rõ trong bài viết tiếp theo Shell - Special Variables



- Copyright © Lập trình hệ thống nhúng Linux . Powered by Luong Duy Ninh -