5
Shell逐行读取、解析并export变量实践
source link: https://mryqu.github.io/post/shell%E9%80%90%E8%A1%8C%E8%AF%BB%E5%8F%96%E8%A7%A3%E6%9E%90%E5%B9%B6export%E5%8F%98%E9%87%8F%E5%AE%9E%E8%B7%B5/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Shell逐行读取、解析并export变量实践 - Mryqu's Notes
setenv.yaml示例
MY_HOME: /local/install/myhome
MY_JAVA_HOME: $MY_HOME/jre/bin
test.ksh示例
#!/bin/ksh
getCustEnv() {
# 除了while read 也可以使用for var,但是需要更改IFS为换行符
cat setenv.yaml | while read line; do
line=$(echo $line | grep -v "^\s*#" | grep ":")
if [ ! -z $line ]; then
key=$(echo $line | cut -d: -f1 | sed -e 's/^\s*//' -e 's/\s*$//')
val=$(echo $line | cut -d: -f2 | sed -e 's/^\s*//' -e 's/\s*$//')
echo "line=$line"
echo "key=$key"
echo "val=$val"
if [ ! -z $key ]; then
echo "export $key=$val"
# 不可以直接执行export,否则变量值还是字符串,例如MY_JAVA_HOME变量值仍为$MY_HOME/jre/bin,而不是/local/install/myhome/jre/bin
eval export $key=$val
# 变量的二次引用 这里${!key}不好使
eval newVal=\${$key}
echo "$key=$newVal"
fi
echo ""
fi
done
}
getCustEnv
标题:Shell逐行读取、解析并export变量实践
作者:mryqu
声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 CN 许可协议。转载请注明出处!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK