使用脚本读取 Unix 属性文件



我的属性文件:

a.prop  
user=abc  
location=home
user=xyz  
location=roamer

我需要读取 a.prop 并将用户和位置保留在变量中,以便我可以将它们作为参数传递给我的其他脚本 (check.sh(。

需要为所有用户/位置列表调用 check.sh。

我不想使用 AWK

这是一个极其脆弱、不明智的解决方案,它为配置的每个节调用一个函数,但需要输入的确切格式,并且容易受到许多攻击媒介的攻击。 使用(或最好不使用(风险自负!

#!/bin/bash
foo() { echo "user is $user, location is $location"; }
eval "$(sed -e '/^$/s//foo/' input; echo foo)"

你最好对输入进行预处理,并且愿意使用 awk 会有所帮助。

未经测试

while read -r line; do
    key=${line%%=*}          # the left-hand-side of the =
    case $key in
        user) user=${line#*=} ;;
        location) location=${line#*=} ;;
        *) continue ;;   # skip this line
    esac
    if [[ -n $user ]] && [[ -n $location ]]; then
        echo "have user=$user and location=$location" 
        check.sh "$user" "$location"
        unset user location
    fi
done < a.prop

这个版本有点不安全:假设属性是有效的 shell 变量赋值。

while read -r line; do
    [[ $line != *=* ]] && continue
    declare "$line"
    if [[ -n $user ]] && [[ -n $location ]]; then
        echo "have user=$user and location=$location" 
        check.sh "$user" "$location"
        unset user location
    fi
done < a.prop

或者,假设"用户"始终出现在"位置"之前

grep -E '^(user|location)=' a.prop | 
  while read userline; read locline; do 
    declare "$userline"
    declare "$locline"
    echo "have user=$user and location=$location"
    check.sh "$user" "$location"
  done

最新更新