特殊字元和解析BUG - Bashscript

特殊字元和解析BUG - Bashscript
Failed to parse arguments: Argument to "--command/-e" is not a valid command: Text ended before matching quote was found for ". (The text was '"cpulimit')

這是我在終端機中運行以下腳本時得到的結果

    #!/bin/bash
read -p "Which program u want to limit its processes?" ProgrameName
read -p "Which limitation percentage u want for it ?" limitationPercentage  

getAllPIDRunUnderThisProgram=$( ps -e | grep "$ProgrameName" | awk '{print $1;}')
for i in $getAllPIDRunUnderThisProgram
   do
    gnomeTab+="  --tab -e \"cpulimit -p $i -l $limitationPercentage \" "  
   done

gnome-terminal $gnomeTab

由於第 8 行中的雙引號,他無法解析必須使用的轉義字元“\” gnomeTab+=" --tab -e \"cpulimit -p $i -l $limitationPercentage \" ",因此是否有解決方案使用雙引號,因為它們必須在之後使用,--tab -e " some commands "並且不會出現解析問題?

答案1

您可以將第一行變更為

#!/bin/bash -xv

讓 shell 向您顯示它如何解釋參數。

eval您應該使用陣列來累積選項,而不是轉義(這會導致):

for i in $getAllPIDRunUnderThisProgram ; do
    gnomeTab+=(--tab -e "cpulimit -p $i -l $limitationPercentage")  
done

echo "${gnomeTab[@]}"

相關內容