Read lines from File in Bash and parse words into variables for mailx parameters

旧时模样 提交于 2019-12-01 19:54:24

Give this a shot:

head -n 4 mail.txt | while read from to subject body; do
    mailx -s "$subject" -t "$to" -r "$from" <<< "$body"
done
  • head -n 4 reads up to four lines from your text file.
  • read can read multiple variables from one line, so we can use named variables for readability.
  • <<< is probably what you want for the redirection, rather than <. Probably.

The above while loop works well as a simple alternative to sed and awk if you have a lot of control over how to display the lines of text in a file. the read command can use a specified delimiter as well, using the -d flag.

Another simple example:

I had used mysql to grab a list of users and hosts, putting it into a file /tmp/userlist with text as shown:

user1 host1
user2 host2
user3 host3

I passed these variables into a mysql command to get grant info for these users and hosts and append to /tmp/grantlist:

cat /tmp/userlist | while read user hostname;
do
  echo -e "\n\nGrabbing user $user for host $hostname..."
  mysql -u root -h "localhost" -e "SHOW GRANTS FOR '$user'@$hostname" >> /tmp/grantlist
done
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!