---
# System prepended metadata

title: 程式流程

---

# 程式流程

## if.sh (整數和字串)

```=
#!/bin/bash
export LANG=C

x=1

if [ ${x} -eq 1 ]; then    #如果x相等於1
    echo "yes"             #印出yes。本例會印出yes
else
    echo "no"              #其餘情況印出no
fi                         #關閉if語句


str="linux"

if [ "${str}" == "apple" ]; then  #如果字串是apple
    echo 1                        #印出1
else
    echo 2                        #其餘情況印出2。本例會印出2，因為宣告的字串是linux，
                                   與apple不符
fi                                #關閉if語句
```
```
student$ chmod +x if.sh
```


> 修改 `x` 查看變化


## if-string.sh (String)

```=
#!/bin/bash

x=c
if [ "${x}" == "a" ]; then
    echo "hello string: a"
elif [ "${x}" == "b" ]; then
    echo "hello string: b"
else
    echo "World string"
fi
```

```
student$ chmod +x if-string.sh
```

> 修改 `x` 查看變化


> https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
> https://tldp.org/LDP/abs/html/comparison-ops.html

## 附註
   -eq 相等於
   -ne 不等於
   -gt 大於
   -ge 大於等於
   -lt 小於
   -le 小於等於
   
## for

* for

    ```=
    for i in 1 2 3 4
    do
        echo ${i}
    done                  #本例會依序印出1 2 3 4，一行1個數字，共印4行
    ```

* for + if

    ```=
    for d in 1 2 3 4 5
    do
        if [ ${d} -eq 3 ]; then
            continue
        elif [ ${d} -eq 4 ]; then
            break
        else
            echo ${d}
        fi              #本例會分兩行印出1 2
    done

    ```
    
## while

* while

    ```=
    c=1
    while [ ${c} -lt 10 ]
    do
        echo ${c}
        
        ((c++))
    done
    ```
    
* while-infinite
    
    ```=
    c=1
    while true
    do
        echo ${c}
        ((c++))
        
        if [ ${c} -gt 10 ]; then
            break
        fi
    done
    ```
    
## case

* case
    ```=
    c="a b"
    case ${c} in
        1)
            echo "Hello 1"
        ;;
        2)
            echo "Hello 2"
        ;;
        3)
            echo "Hello 3"
        ;;
        "a b")
            echo "Hello a, b"
        ;;
        *)
            echo "Not match"
        ;;
    esac
    ```
    
## function

* case + function

    ```=
    function say {
        words="${1}"
        
        echo "Hello ${words}"
    }
    
    c="a b"
    case ${c} in
        1)
            say "1"
        ;;
        2)
            say "2"
        ;;
        3)
            say "3"
        ;;
        "a b")
            say "a b"
        ;;
        *)
            echo "Not match"
        ;;
    esac
    ```

![](https://i.imgur.com/jNTpN7H.png)

## 變數

```
student$ myfile=$(ls /)

student$ echo ${myfile}
```