bash 脚本中读取一个文件名362


在 Bash 脚本中,经常需要读取一个文件名作为输入。可以使用以下方法之一来实现此目的:

1. 使用 shift 命令

shift 命令可将第一个参数从命令行参数列表中删除,并将其存储在 $1 变量中。例如,以下脚本将第一个命令行参数作为文件名并打印其内容:```bash
#!/bin/bash
shift
echo "File contents:"
cat $1
```

2. 使用 read 命令

read 命令可从标准输入读取一行并将其存储在指定的变量中。例如,以下脚本提示用户输入文件名并将其存储在 $filename 变量中:```bash
#!/bin/bash
echo "Enter the file name:"
read filename
echo "File contents:"
cat $filename
```

3. 使用 getopts 命令

getopts 命令可解析命令行选项并将其存储在指定的变量中。例如,以下脚本使用 -f 选项解析文件名并将其存储在 $filename 变量中:```bash
#!/bin/bash
while getopts f: option; do
case $option in
f) filename=$OPTARG;;
?) echo "Invalid option -$OPTARG"; exit 1;;
esac
done
echo "File contents:"
cat $filename
```

4. 使用 readlink 命令

readlink 命令可解析符号链接并返回其目标文件或目录的绝对路径。例如,以下脚本使用 readlink 命令解析名为 link 的符号链接并将其目标存储在 $filename 变量中:```bash
#!/bin/bash
filename=`readlink link`
echo "File contents:"
cat $filename
```

5. 使用 file 命令

file 命令可确定文件类型。例如,以下脚本使用 file 命令确定名为 file 的文件类型并将其存储在 $filetype 变量中:```bash
#!/bin/bash
filetype=`file file`
echo "File type: $filetype"
```

6. 使用 stat 命令

stat 命令可提供有关文件或目录的信息。例如,以下脚本使用 stat -f 命令获取名为 file 的文件的访问时间并将其存储在 $access_time 变量中:```bash
#!/bin/bash
access_time=`stat -f "%a" file`
echo "Access time: $access_time"
```

7. 使用 dirname 命令

dirname 命令可获取文件或目录的父目录。例如,以下脚本使用 dirname 命令获取名为 file 的文件所在目录并将其存储在 $dirname 变量中:```bash
#!/bin/bash
dirname=`dirname file`
echo "Parent directory: $dirname"
```

8. 使用 basename 命令

basename 命令可获取文件或目录的名称,而不包括路径。例如,以下脚本使用 basename 命令获取名为 file 的文件的文件名并将其存储在 $basename 变量中:```bash
#!/bin/bash
basename=`basename file`
echo "File name: $basename"
```

9. 使用 realpath 命令

realpath 命令可解析符号链接和相对路径,并返回文件的绝对路径。例如,以下脚本使用 realpath 命令获取名为 link 的符号链接的绝对路径并将其存储在 $realpath 变量中:```bash
#!/bin/bash
realpath=`realpath link`
echo "Absolute path: $realpath"
```

10. 使用 find 命令

find 命令可搜索文件和目录。例如,以下脚本使用 find 命令搜索当前目录中名为 file 的文件并打印其绝对路径:```bash
#!/bin/bash
find . -name file -print0 | xargs -0 realpath
```

2024-12-25


上一篇:Linux 命令行和 Bash 脚本编程圣经:下载与安装

下一篇:Bash 脚本编译成可执行文件