Bash 語法筆記

## 一個簡單的示例
新建一個文件,`test.sh`,輸入如下代碼:bash

```
#!/bin/bash
echo "hello, $USER. I wish to list some files of yours"
echo "listing files in the current directory, $PWD"
ls # 列出當前目錄全部文件
```
這個簡單的示例說明幾點內容:less

1. `#!/bin/bash` 表示bash文件的開頭
2. `echo` 語句
3. `ls` 語句
4. `#`表示註釋string

## 變量it

```
#!/bin/bash
X=""
if [ -n $X ]; then # -n 用來檢查變量是否非空
echo "the variable X is not the empty string"
fi
```
這個示例說明幾點內容:io

1. `#!/bin/bash` 表示bash文件的開頭
2. `X=""`變量的定義方式
3. `if` 語句
4. `$X` 變量的引用方式test

> 注意: 單引號和雙引號的區別,變量名會在雙引號中展開,單引號中則不會。
```
#!/bin/bash
echo -n '$USER=' # -n選項表示阻止echo換行
echo "$USER"
echo "\$USER=$USER" # 該命令等價於上面的兩行命令
```
> 注意: 大括號保護變量
```
#!/bin/bash
X=ABC
echo "${X}abc"
```變量

## 條件語句, if/then/elif
語法:
```
if condition
then
statement1
statement2
..........
else
statement3
fi
```file

示例:
```
#!/bin/bash
X=3
Y=4
empty_string=""
if [ $X -lt $Y ] # is $X less than $Y ?
then
echo "$X=${X}, which is smaller than $Y=${Y}"
fi

if [ -n "$empty_string" ]; then
echo "empty string is non_empty"
fi

if [ -e "${HOME}/.fvwmrc" ]; then # test to see if ~/.fvwmrc exists
echo "you have a .fvwmrc file"
if [ -L "${HOME}/.fvwmrc" ]; then # is it a symlink ?
echo "it's a symbolic link
elif [ -f "${HOME}/.fvwmrc" ]; then # is it a regular file ?
echo "it's a regular file"
fi
else
echo "you have no .fvwmrc file"
fi
```循環

## 循環語法

### for ```#!/bin/bashfor X in red green bluedo echo $Xdone```### while```#!/bin/bashX=0while [ $X -le 20 ]do echo $X X=$((X+1))done```

相關文章
相關標籤/搜索