3

我尝试自动设置我的环境。这样做我需要在终端中打开几个选项卡并执行命令。选项卡应该有一个标题来区分它们。该脚本应该只在选项卡中写入命令而不执行。

该脚本需要一个输入文件 start.txt。这将逐行处理 - 每行首先包含终端选项卡的标题,并用逗号分隔命令。

通过非常简单的 gnome-terminal 调用,将显示标题:

gnome-terminal -- tab --title=test1 -e top --tab --title=test2 top

但是当执行复杂的命令时,这将不起作用,并且不会设置标题。

这是整个代码:

#!/bin/bash

# define variable which needs to be executed
cmdline="gnome-terminal"
# define input file
file="cat start.txt"
# define run_command script
destdir=/home/ank1abt/Documents/run_command.sh


# create if not already existing and change permissions
touch $destdir
chmod 755 $destdir

# read file an process line by line 
# each line contains first the title and with comma separated the command for a new tab in a terminal
$file | \
while read row; do
  #extract tab title and command   
  title=$(echo $row | awk -F","  '{print $1}')
  cmd=$(echo $row | awk -F","  '{print $2}')  
  set_title="export PS1='\[\e]0;"$title"\a\]\${debian_chroot:+(\$debian_chroot)}\u@\h:\w\$'"      
  #cmdline=$cmdline\ "--tab --title="$title" -e top"
  cmdline=$cmdline\ "--tab --title="$title" -e \"bash -c \\\" echo "$title"; echo export PS1='\[\e]0;"$title"\a\]\\\${debian_chroot:+(\\\$debian_chroot)}\u@\h:\w\$';echo "$cmd"; exec bash\\\"\""
  echo $cmdline   
  # command will be written to a file
  echo "$cmdline" > $destdir
done

# execute the file with the command
exec "./run_command.sh"

与此同时,我尝试了一种解决方法。还有另一个有趣的命令,您可以使用它在选项卡中设置选项卡标题,然后可以在选项卡中执行或直接写在那里,以便用户可以复制和执行它:

导出 PS1='[\e]0;任务\a]${debian_chroot:+($debian_chroot)}\u@\h:\w$'

但是使用当前代码,以下命令将被写入 run_command 脚本:

gnome-terminal --tab --title=test1 -e "bash -c \" echo test1; echo export PS1='[\e]0;test1\a]\${debian_chroot:+(\$debian_chroot)}\u@\h:\w$'; 回声顶部;执行 bash\"" --tab --title=test2 -e "bash -c \" echo test2; echo export PS1='[\e]0;test2\a]\${debian_chroot:+(\$debian_chroot)}\u@\h:\w$'; 回声顶部;执行 bash\""

当您只是复制此命令并在终端中执行它时,选项卡将显示导出命令,但不包含在单引号中,然后它将不起作用。

导出 PS1=[\e]0;任务\a]${debian_chroot:+($debian_chroot)}\u@\h:\w$

当然,我更喜欢让 gnome-terminal 命令的标题选项工作,但如果这不可能,我会很高兴任何提示如何在单引号的选项卡中使用 PS1 的导出值。我已经尝试用 \ 或几个 \ 来逃避它,但没有成功。

4

1 回答 1

1

由于您正在将命令写入文件然后执行它,因此您需要额外的引用级别。在脚本的中间部分试试这个:

while read row; do
  #extract tab title and command   
  title=$(echo $row | awk -F","  '{print $1}')
  cmd=$(echo $row | awk -F","  '{print $2}')  
  cmdline=$cmdline\ "--tab --title='$title' -e '$cmd'"
  echo $cmdline   
  # command will be written to a file
  echo "$cmdline" > $destdir
done
于 2012-11-12T19:05:16.897 回答