探索Bash脚本的乐趣与实用技巧
立即解锁
发布时间: 2025-08-12 00:05:47 阅读量: 2 订阅数: 6 


快速上手Linux:初学者指南
### 探索Bash脚本的乐趣与实用技巧
#### 1. 向脚本传递参数
在Bash脚本中,除了从用户那里读取输入,还可以向脚本传递参数。例如,创建一个名为`size2.sh`的Bash脚本,它的功能与`size.sh`相同,但不是从用户那里读取文件,而是将文件作为参数传递给脚本。
```bash
#!/bin/bash
filesize=$(du -bs $1| cut -f1)
echo "The file size is $filesize bytes"
```
操作步骤如下:
1. 创建`size2.sh`脚本,并将上述代码复制进去。
2. 使脚本可执行:`chmod a+x size2.sh`
3. 运行脚本:`size2.sh /home/elliot/size.sh`
这里只使用了一个参数,用`$1`引用。也可以传递多个参数,例如创建`size3.sh`脚本,它接受两个文件(两个参数)并输出每个文件的大小。
```bash
#!/bin/bash
filesize1=$(du -bs $1| cut -f1)
filesize2=$(du -bs $2| cut -f1)
echo "$1 is $filesize1 bytes"
echo "$2 is $filesize2 bytes"
```
操作步骤:
1. 创建`size3.sh`脚本并复制代码。
2. 使脚本可执行:`chmod a+x size3.sh`
3. 运行脚本:`size3.sh /home/elliot/size.sh /home/elliot/size3.sh`
一般来说,脚本和参数的对应关系如下:
| 脚本及参数 | 引用方式 |
| --- | --- |
| bash_script.sh argument1 argument2 argument3 ... | $1 $2 $3 |
#### 2. 使用if条件语句
可以通过条件`if`语句让Bash脚本在不同场景下表现不同,从而为脚本添加智能。`if`条件语句的一般语法如下:
```bash
if [ condition is true ]; then
do this ...
fi
```
例如,创建一个`empty.sh`脚本,用于检查文件是否为空。
```bash
#!/bin/bash
filesize=$(du -bs $1 | cut -f1)
if [ $filesize -eq 0 ]; then
echo "$1 is empty!"
fi
```
操作步骤:
1. 创建`empty.sh`脚本并复制代码。
2. 使脚本可执行:`chmod a+x empty.sh`
3. 创建一个空文件:`touch zero.txt`
4. 运行脚本:`./empty.sh zero.txt`
如果文件不为空,脚本不会有输出。可以使用`if-else`语句修改脚本,使其在处理非空文件时也能输出信息。
```bash
#!/bin/bash
filesize=$(du -bs $1 | cut -f1)
if [ $filesize -eq 0 ]; then
echo "$1 is empty!"
else
echo "$1 is not empty!"
fi
```
还可以使用`elif`(else-if)语句创建多个测试条件。例如,创建`filetype.sh`脚本,用于检测文件类型。
```bash
#!/bin/bash
file=$1
if [ -f $1 ]; then
echo "$1 is a regular file"
elif [ -L $1 ]; then
echo "$1 is a soft link"
elif [ -d $1 ]; then
echo "$1 is a directory"
fi
```
操作步骤:
1. 创建`filetype.sh`脚本并复制代码。
2. 使脚本可执行:`chmod a+x filetype.sh`
3. 创建一个软链接:`ln -s /tmp tempfiles`
4. 测试不同类型的文件:
- `./filetype.sh /bin`
- `./filetype.sh zero.txt`
- `./filetype.sh tempfiles`
所有的测试条件可以通过`man test`命令查看。
#### 3. Bash脚本中的循环
循环是Bash脚本的一个强大功能。
##### 3.1 使用for循环
`for`循环有几种不同的语法。如果熟悉C++或C编程,会认识以下`for`循环语法:
```bash
for ((initialize ; condition ; increment)); do
// do something
done
```
例如,使用上述C风格的语法,以下`for`循环将输出20次“Hello World”:
```bash
for ((i = 0 ; i < 20 ; i++)); do
echo "Hello World"
done
```
创建`hello20.sh`脚本:
```bash
#!/bin/bash
for ((i = 0 ; i < 20 ; i++)); do
echo "Hello World"
done
```
操作步骤:
1. 创建`hello20.sh`脚本并复制代码。
2. 使脚本可执行:`chmod a+x hello20.sh`
3. 运行脚本:`hello20.sh`
也可以使用范围语法:
```bash
for i in {1..20}; do
echo "Hello World"
done
```
范围语法在处理文件列表时特别有用。例如,将所有`.doc`文件的扩展名重命名为`.document`。
``
0
0
复制全文
相关推荐










