bash将字符串传递给" gnome-terminal -e"

时间:2015-08-28 17:27:14

标签: string bash escaping

这个问题看起来像Opening multiple tabs in gnome terminal with complex commands from a cycle,但我正在寻找更通用的解决方案。

我有一个调用脚本的C程序" xvi"有参数。每个参数最初都用引号括起来(''')并且参数中的每个引号都是隔离的并且是反斜杠(这种格式是先决条件)ex:

xvi 'a file' 'let'\''s try another'

脚本xvi必须使用" -e vim args"

启动gnome-terminal

使用xterm而不是gnome-terminal,这很容易,因为xterm假设" -e"是最后一个参数,并将所有尾部传递给shell,因此以下是正常的:

exec /usr/bin/xterm -e /usr/bin/vim "$@"

对于gnome-terminal," -e"是一种选择,我们需要包装'一个参数中的整个命令行。这就是我所做的,这是可以的:将每个参数包含在双引号内(\" arg \")并反斜杠参数中的任何双引号:

cmd="/usr/bin/vim"
while [ "$1" != "" ] ; do
  arg=`echo "$1" | sed -e 's/\"/\\\"/g'`
  cmd="$cmd \"$arg\""
  shift
done
exec gnome-terminal --zoom=0.9 --disable-factory -e "$cmd"

同样,这很好用,我对此感到非常满意。

问题:有没有更好的解决方案,避免循环?

由于

2 个答案:

答案 0 :(得分:0)

未经测试,但您可能会让printf '%q'完成工作:

exec gnome-terminal --zoom=0.9 --disable-factory -e "$(printf '%q ' "$@")"

答案 1 :(得分:0)

我知道这个帖子已经老了但是最近我有类似的需求,我创建了一个bash脚本来启动多个标签并在每个标签上运行不同的命令:

#!/bin/bash

# Array of commands to run in different tabs
commands=(
    'tail -f /var/log/apache2/access.log'
    'tail -f /var/log/apache2/error.log'
    'tail -f /usr/local/var/postgres/server.log'
)

# Build final command with all the tabs to launch
set finalCommand=""
for (( i = 0; i < ${#commands[@]}; i++ )); do
    export finalCommand+="--tab -e 'bash -c \"${commands[$i]}\"' "
done

# Run the final command
eval "gnome-terminal "$finalCommand

您只需要在数组中添加命令并执行。

要点链接:https://gist.github.com/rollbackpt/b4e17e2f4c23471973e122a50d591602