首页 > 解决方案 > 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 

标签: bashrsync

解决方案


如何使用 bash 扫描文本文件中的特定字符串,然后使用 if then 语句根据字符串执行特定命令?

您可以在 if 语句中使用命令。现在该命令的退出代码用于确定真假。对于对文件的查询的简单搜索,您可以使用 grep。

if grep -q "$QUERY_STRING" file; then 

-q 用于防止 grep 的任何输出以标准输入结尾。


推荐阅读