简体   繁体   中英

bash passing strings to “gnome-terminal -e”

this question looks like Opening multiple tabs in gnome terminal with complex commands from a cycle , but I am looking for a more generic solution.

I have a C program that calls a script "xvi" with arguments. Each argument is originally enclosed within quotes (''') and each quote in an argument is isolated and back-slashed (this format is a prerequisite) ex:

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

The script xvi must launch gnome-terminal with "-e vim args"

With xterm instead of gnome-terminal, this is easy because xterm assumes that "-e" is the last argument and passes all the tail to the shell, so the following is OK:

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

For gnome-terminal, "-e" is an option among others and we need to 'package' the whole command line in one argument. This is what I have done, which is OK: Enclose each argument within double quotes(\\"arg\\") and backslash any double quote within an argument:

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"

Again, this works fine and I am nearly happy with that.

Question: Is there any nicer solution, avoiding the loop?

Thanks

未经测试,但您可能可以将printf '%q'带入该工作:

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

I know this thread is old but recently I had a similar need and I created a bash script to launch multiple tabs and run different commands on each of them:

#!/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

You just need to add your commands in the array and execute.

Gist link: https://gist.github.com/rollbackpt/b4e17e2f4c23471973e122a50d591602

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM