请在下面找到简化的bash脚本parseArg.sh:-
#!/usr/bin/env bash
function parse(){
local propsFile=$1
echo "search file is : >$propsFile<"
while IFS='=' read -r packageKey packageValue;
do
echo "package value is >$packageValue<"
packageProcessor $packageValue
echo "---------------------------------------------------------"
done < "$propsFile"
}
function packageProcessor(){
echo "Total args : $#"
echo "All args value : >$@<"
for arg in "$@"
do
echo "$arg"
done
}
$@
以下是同一目录中的配置文件repos.conf:-
cm5-centos6.6="https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""
当我在同一目录中执行以下命令时:-
sh parseArg.sh解析repos.conf
我原本希望有6个参数,但是总共有10个参数。 以下是实际输出:-
search file is : >repos.conf<
package value is >"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""<
Total args : 10
All args value : >"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""<
"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/
cm5-centos6.6
cm5/centos6.6
cm5/centos6.6
cm5-centos_6_6
"Cdh
5
for
CentOS
6.6""
---------------------------------------------------------
答案 0 :(得分:0)
在parse
函数中,变量packageValue
将包含一个值如下的字符串:
"https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6""
该变量的值中包含前导和尾随引号。该字符串中的引号是普通字符。
将其解析为6个单独组件的唯一可行方法是使用eval
强制外壳程序遵守“内部”引号。首先,您必须删除开头和结尾的引号:
tmp=${packageValue#\"}
packageValue=${tmp%\"}
packageProcessor "$packageValue"
然后,在packageProcessor
函数中,您将必须使用eval
将字符串分配为数组,但是您需要暂时禁用文件名生成:您想利用分词,但不受路径扩展的影响。
set -f
eval "elements=($1)"
set +f
现在您可以
declare -p elements
for arg in "${elements[@]}"; do echo "$arg"; done
说了这么多,就不要做。这本质上是不安全的。使用不会将您暴露给eval
的不安全调用而只是分割数据的数据存储格式。
如果您完全可以控制该配置文件的内容,请使用Shell语法使其成为您可以获取的脚本:
declare -a cm5_centos_6_6=(https://archive.cloudera.com/cm5/redhat/6/x86_64/cm/5/ cm5-centos6.6 cm5/centos6.6 cm5/centos6.6 cm5-centos_6_6 "Cdh 5 for CentOS 6.6")