如何将bash中的查询字符串解析为if then语句

时间:2019-01-25 20:23:36

标签: bash rsync

如何使用bash扫描文本文件中的特定字符串,然后使用if then语句根据字符串执行特定命令? 我正在尝试使用rsync从HTML表单输出的查询字符串中备份一些树莓pi。我对bash的经验很少,并且我一直在几天后不断尝试这段代码,所以我很乐意为您提供一些建议。

QUERY_STRING将包含类似于“ Backup_To_Comp = tasting-side_backup&subbtn = Submit”的内容,而“ Tasting-side_backup”将被替换为其他选定的径向按钮标签。

#!/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 

1 个答案:

答案 0 :(得分:0)

  

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

您可以在if语句中使用命令。现在,该命令的退出代码用于确定是或否。为了简单地查询文件查询,可以使用grep。

if grep -q "$QUERY_STRING" file; then 

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