> For the complete documentation index, see [llms.txt](https://easonwang.gitbook.io/web_advance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easonwang.gitbook.io/web_advance/linux_shi_yong_zhi_ling/shell-script-jiao-xue.md).

# Shell Script 教學

## 1.暫停秒數

> 注意:單位為秒，非毫秒

```
sleep 1;
```

## 2.執行指令存為變數

```
a=$(du -sh ./Images)
echo $a
```

如果裡面有包含多可指令

```
name=$(basename `pwd`)
echo $name
```

## 3.等於之後不可有空格

```
a="Hello World!"
echo $a
```

> 如果a = "..."，則會錯誤

## 4.運算要用變數加兩個括號

```
b=10000
a=2000
a=$(($a + $b))
```

## 5.引入另一個shell script Function

test1.sh

```
#!/bin/bash
func1() {
   fun=$1
   book=$2
   printf "fun=%s,book=%s\n" "${fun}" "${book}"
};

func2() {
   fun2=$1
   book2=$2
   printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
};
```

test2.sh

```
. ./test1.sh
func1 love horror
func2 ball mystery
```

執行 :

```
sudo vim test2.sh
```

## 6. function 參數

file.sh

```bash
test() {
  echo $0
  echo $1
  echo $2
}

test 123 234
```

執行 `./file.sh`

回傳&#x20;

```
./file.sh
123
234
```

## 7. for loop

```
projects=( 
    "test1" 
    "test2" 
)

for i in "${projects[@]}"
do
   echo $i
done
```

> 回傳&#x20;
>
> ```
> test1
> test2
> ```

## 8. If else

```bash
if echo "$name" | grep "playtable-discovery"
then
    goUpperDirectory
else
    echo "ERROR: Incorrect folder"
    exit 1
fi
```

## 9. 退出程式

```bash
exit 1
```

## 10. 查看檔案或資料夾是否存在

```bash
 [ -f "/path/to/dir/filename" ];
 
 [ -d "/path/to/dir" ];
```

## grep

> 用來查找字串，記得他匹配到就會把整行回傳

#### &#x20;用法

```
grep 關鍵字 檔案1 檔案2 ...
```

查找所有相關檔案

```
grep words.. /etc/*.conf
```
