繁体   English   中英

Bash脚本从文本文件读取变量

[英]Bash script to read variable from text file

我想在文本文件中包含以下内容

name=missy email=missy@example.com

是否有可能将其读入文本文件并能够调用变量$ name和$ email

或最好的方法是什么?

谢谢你的帮助

当然,这是想到的第一种方式:

#!bash
# set for loop separator to newline
IFS=$'\n'
# loop through each line in the file
for userline in $(cat email_list.txt); do
    # Cut delimiter is a space for the next two lines
    # echo the line into cut, grab the first field as the user
    user=$(echo "$userline" | cut -d' ' -f1)
    # echo the line into cut, grab the second field as the email
    email=$(echo "$userline" | cut -d' ' -f2)

    # Set the delimiter an =, grab field 2
    user=$(echo "$user" | cut -d'=' -f2)
    # Set the delimiter an =, grab field 2
    email=$(echo "$email" | cut -d'=' -f2)

    echo "Username: ${user}, email address: ${email}"
done

email_list.txt:

name=missy email=missy@example.com
name=joe email=joe@smoe.com

输出:

Username: missy, email address: missy@example.com
Username: joe, email address: joe@smoe.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM