简体   繁体   English

bash脚本中的变量格式检查

[英]Variable formatting check in bash script

I have a real simple script to update a table based on a flat file but am concerend as the list keeps getting longer and longer a non valid formatted variable will get introduced and cause issues. 我有一个真正简单的脚本来更新基于平面文件的表,但是很礼貌,因为列表会越来越长,一个无效的格式化变量将被引入并引起问题。

#!/bin/bash

OLDIFS=$IFS
IFS=,
file1=file.csv

while read mac loc; do

dbaccess modemdb <<EndOfUpdate 2>/dev/null
UPDATE profile 
SET localization= '$loc' 
WHERE mac_address = '$mac';
EndOfUpdate

done <"$file1"
IFS=$OLDIFS

The file contents are as such. 文件内容就是这样。

12:BF:20:1B:D3:22,RED-1234
12:BF:20:2D:FF:1B,BLUE-1234
12:BF:20:ED:74:0D,RED-9901
12:BF:20:02:69:7C,GREEN-4321
12:BF:20:02:6B:42,BROWN
12:BF:20:ED:74:0D,BLACK

What I am having difficulty with is how can I set a format check of the $mac and $loc variables so if they don't match it stops running. 我遇到的困难是如何设置$ mac和$ loc变量的格式检查,因此如果它们不匹配,它将停止运行。 the $loc can be any 19 digits so just need to make sure its not null and not longer. $ loc可以是任何19位数字,因此只需确保其不为null和更长。 The mac address needs to be not null and in the format as in the file. mac地址必须不为null,并且格式必须与文件中的格式相同。 I found reference in another post to this check but not sure how to integrate. 我在另一篇文章中找到了对此检查的参考,但不确定如何集成。

`[[ "$MAC_ADDRESS" =~ "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$" ]]`

Looking for help on how to create the validations. 寻找有关如何创建验证的帮助。

Thanks, 谢谢,

Check MAC address with regex: 使用正则表达式检查MAC地址:

#!/bin/bash

file1=file.csv

while IFS="," read mac loc; do
  if [[ "$mac" =~ ^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$ ]]; then
    dbaccess modemdb <<EndOfUpdate 2>/dev/null
UPDATE profile 
SET localization= '$loc' 
WHERE mac_address = '$mac';
EndOfUpdate
  else
    echo "Error: $mac"
  fi
done <"$file1"

Your regex is for bash only a string if you use quotation marks. 如果使用引号,则正则表达式仅用于bash字符串。

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

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