bash - How to parse query string in bash into if then statement
问题描述
How can I use bash to scan for a specific string of characters in a text file and then use an if then statement to execute a specific command depending on the string? I am trying to use rsync to back up some raspberry pis from a query string output from an HTML form. I have minimal bash experience and I have been poking and prodding this code for days now and I would love for some advice.
QUERY_STRING will contain something similar to "Backup_To_Comp=tasting-side_backup&subbtn=Submit" with the "Tasting-side_backup" being swapped for other radial button tags as selected.
#!/bin/bash
echo "Content-type: text/html"
echo ""
echo "$QUERY_STRING" > /var/www/cgi-bin/scan.txt
BackupToCompFrom=`echo "$QUERY_STRING" | sed -n 's/^.*Backup_To_Comp=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"`
echo "<html><head><title>What You Said</title></head>"
echo "<body>Here's what you said:"
echo "You entered $BackupToCompFrom in from field."
sleep 1
file="/var/www/cgi-bin/scan.txt"
##echo "$QUERY_STRING"
while IFS='' read -r line || [[ -n "$line" ]];
do
if [[ $line = "tasting-side_backup" ]]; then
echo "GotIt."
rsync pi@192.168.1.1:/home/pi/screenly_assets /home/pi/Downloads
elif [[ $line = "~tasting-main"* ]]; then
print "Tasting Main"
elif [[ $line = "~lodge"* ]]; then
print "Lodge"
elif [[ $line = "~barn"* ]]; then
print "Barn"
else
print "Please select a pi to copy from!"
fi
done
解决方案
如何使用 bash 扫描文本文件中的特定字符串,然后使用 if then 语句根据字符串执行特定命令?
您可以在 if 语句中使用命令。现在该命令的退出代码用于确定真假。对于对文件的查询的简单搜索,您可以使用 grep。
if grep -q "$QUERY_STRING" file; then
-q 用于防止 grep 的任何输出以标准输入结尾。
推荐阅读
- php - 有没有更好的方法来使用 PHP Parser 删除除 Function_ 节点之外的所有其他代码?
- python - 解析文本文件并转换为 csv
- intellij-idea - intellij:数据库工具工具访问问题
- django - 静态文件 DJANGO
- python - 使用 Python 和 Boto3 从 S3 读取多个 CSV 文件
- powershell - 如何在计划任务中执行 Get-CrmConnection
- r - 返回顶点列表
- javascript - 如何通过 YouTube Data API 获取特定帐户(频道)发布的评论?
- javascript - 如何使用jquery触发dataTable搜索窗格的onclick事件?
- c# - 同时缩放两个游戏对象