簡體   English   中英

為什么 bash 腳本在變量擴展上添加單引號?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM