Shell脚本:为新的gnome终端选项卡设置标题



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

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

通过一个非常简单的gnome终端调用,标题将显示:

gnome终端--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_chloot)}\u@\h:\w$'

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

gnome terminal--tab--title=test1-e"bash-c\"echo test1;回响出口PS1='[\e]0;test1\a]\${debian_chroot:+(\$debian_chroot)}\u@\h:\w$';回波顶部;exec bash\"--tab--title=test2-e"bash-c\"echo test2;回波输出PS1='[\e]0;test2\a]\${debian_chroot:+(\$debian_chroot)}\u@\h:\w$';回波顶部;exec bash\">

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

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

当然,我更喜欢让gnome终端命令的title选项发挥作用,但如果这不可能,我会很高兴看到任何关于如何在单引号中的选项卡中导出PS1的值的提示。我已经尝试过几次逃脱,但都没有成功。

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

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

最新更新