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```

相关文章
相关标签/搜索