2017-12-02 295 views
0

我想读取我的配置文件并获取默认打印机的值。所以在这个例子中,我期望返回结果Zebra_GK420Dbash根据config.ini文件中默认变量的值使用源读取变量

我的config.ini文件,如下所示:

enable_printing=yes 
default_printer=printer1 
printer1=Zebra_GK420D 
printer2=DYMO_LabelWriter_4XL 
create_proof=yes 

我使用以下bash脚本:

1 #!/usr/bin/env bash 
    2 
    3 #Define filename 
    4 fConfig=config.ini 
    5 
    6 #If file exists, read in variables. 
    7 if test -f $fConfig ; then 
    8   source $fConfig 
    9 fi 
10 
11 echo The default_printer is: ${default_printer%?} 
12 
13 echo The name of the default_printer is: $(${default_printer%?}) 

当我运行该脚本,它返回:

The default_printer is: printer1 
./test.sh: line 13: printer1: command not found 

如何我可以修复我的bash脚本,以便它返回以下内容:

The default_printer is: printer1 
The name of the default_printer is: Zebra_GK420D 

请注意,由于config.ini文件托管在Windows驱动器上,因此每行最后会返回\r,所以我使用%?删除每行的最后一个字符。这里的危险在于文件中的最后一行最后没有\r。我可以使用什么来代替%?来只删除\r而不是盲目删除最后一个字符?

谢谢。

+1

如果你修改你的配置文件,以便它不使用DOS行尾,你可以使用间接参数扩展:'$ {!default_printer}'。 (没有修复它,只需要两行'tmp = $ {default_printer%?}; echo $ {!tmp}'。) – chepner

+1

您可以指定要移除的确切字符:'$ {default_printer%$'\ r'} '。但是,我强烈建议只修复该文件,而不要让消费者处理回车。 – chepner

+1

你可以尝试进程替换过滤掉源文件中的回车:'source <(tr -d'\ r'<$ fConfig)' –

回答

0

答案出现在错误消息中:command not found。看看你的第13行:

echo The name of the default_printer is: $(${default_printer%?}) 

$(command)在bash中用来获取命令的输出。所以你明确地要求将打印机名称作为命令执行,并且可以预见,该命令不存在。试试:

echo The name of the default_printer is: ${default_printer%?}