[英]why bash script adds single quotes on variable expansion?
我正在尝试使用 bash 脚本通过 xrandr 添加分辨率,但我不断收到错误消息,这是我的脚本:
#!/bin/bash
out=`cvt 1500 800`
out=`echo $out | sed 's/\(.*\)MHz\(.*\)/\2/g'`
input=`echo $out | sed 's/Modeline//g'`
#echo $input
xrandr --newmode $input
input2=`echo $out | cut -d\" -f2`
#echo $input2
xrandr --addmode VNC-0 $input2
使用 bash -x 运行
input=' "1504x800_60.00" 98.00 1504 1584 1736 1968 800 803 813 831 -hsync +vsync'
+ xrandr --newmode '"1504x800_60.00"' 98.00 1504 1584 1736 1968 800 803 813 831 -hsync +vsync
如果您查看最后一行,它会出于某种原因在开头(“之前”)和“之后”添加单引号 ',为什么?
bash -x
在打印调试输出时添加单引号。
它不会影响您的实际变量值:
out=`cvt 1500 800`
echo $out
# 1504x800 59.92 Hz (CVT) hsync: 49.80 kHz; pclk: 98.00 MHz Modeline "1504x800_60.00" 98.00 1504 1584 1736 1968 800 803 813 831 -hsync +vsync
echo $input
"1504x800_60.00" 98.00 1504 1584 1736 1968 800 803 813 831 -hsync +vsync 98.00 1504 1584 1736 1968 800 803 813 831 -hsync +vsync
实际发生的情况是,当变量被替换时,变量值内的引号不会被解析。
做这种事情的最好方法是使用数组而不是简单的文本变量:
xrandr_opts=() # declaring array
input=`echo $out | sed 's/Modeline//g'`
read -a xrandr_opts <<< $input # splitting $input to array
xrandr --newmode "${xrandr_opts[@]}"
至于您的具体情况,以下更改将起作用:
#!/bin/bash
out=`cvt 1500 800`
out=`echo $out | sed 's/\(.*\)MHz\(.*\)/\2/g'`
input=`echo $out | sed 's/Modeline//g'`
#echo $input
#xrandr --verbose --newmode $input
xrandr_opts=() # declaring array
input=`echo $input | sed 's/\"//g'`
read -a xrandr_opts <<< $input # splitting $input to array
opts_size=`echo ${#xrandr_opts[@]}`
xrandr --newmode `printf \'\"%s\"\' ${xrandr_opts[0]}`
${xrandr_opts[@]:1:$opts_size}
input2=`echo $out | cut -d\" -f2`
#echo $input2
xrandr --verbose --addmode VNC-0 $input2
看起来xrandr --newmode
不接受双引号。 我不能确切地说是什么原因,但至少脚本有效:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.