我们可以定义一个变量,然后从 .txt 文件中读取这个变量的值。这可以通过以下代码实现:
#!/bin/bash
# 定义变量
file="./config.txt"
# 检查文件是否存在
if [ -f "$file" ]
then
# 从文件中读取变量值
username=$(grep "username" $file | cut -d'=' -f2)
password=$(grep "password" $file | cut -d'=' -f2)
# 输出变量值
echo "Username: $username"
echo "Password: $password"
else
echo "$file 不存在."
fi
这个脚本会检查指定的文件是否存在,如果存在就读取文件中的变量值并输出。我们可以在 config.txt 文件中定义类似下面这样的内容:
username=johndoe
password=secret123
当我们运行脚本时,就可以从文件中读取这些变量的值。
下一篇:Bash脚本从URL下载文件