I have a bash script that starts a terminal window with multiple tabs and executes a command in each of the tabs similar to this (and titles aren't supported, I know):

#!/bin/bash

title1="foo"
title2="bar"

cmd1="sleep 1s"
cmd2="cd ~/Desktop"

gnome-terminal --tab --title="$title1" --command="bash -c '$cmd1; $SHELL'" \
               --tab --title="$title2" --command="bash -c '$cmd2; $SHELL'"

In the real script, when the process in one of the tabs dies, I have to restart it, usually. However, pressing the UP key doesn't yield the command used in the script in that tab. This behavior is the same with this script, as if I press up in the first tab I don't get "sleep 1s" but a completely different command I used elsewhere.

Is there a way for the opened tab to keep the $cmd used in the script?

up vote 1 down vote accepted

There should be a more elegant solution than this, but you can try something like:

--command="bash -c 'export HISTFILE=/tmp/hist\$\$; history -s \"$cmd1\";
           history -w; $cmd1; exec $SHELL'"

where the bash is given its own history file hist$$, the $$ having to be escaped to be evaluated later to the pid of the process. history -s saves a string to the history list, and -w saves that to the HISTFILE. The shell is assumed to use this value set in the environment. You may need to add --norc for bash to stop it setting up a different history file from your ~/.bashrc, for example.

  • based on what you wrote I edited the last two lines of the sample script up here into: gnome-terminal --tab --title="$title1" --command="bash --norc -c 'HISTFILE=/tmp/hist\$\$; history -s \"$cmd1\"; history -w; $cmd1; exec $SHELL'" \ (...) but it doesn't seem to work. Moreover I need ~/.bashrc to source some files. I tried with --norc but it still wouldn't work. The files are created in /tmp/ and they have the command, but the up arrow still retrieves the global history. – Laboratorio Cobotica Oct 11 at 14:23
  • 1
    If you type echo $HISTFILE in the final shell do you see the /tmp filename, or is it overridden by your .bashrc? Perhaps you just need to add export in front of HISTFILE=.... I might not have needed to as I already export it. – meuh Oct 11 at 14:37
  • Yep, that did it! Thank you! I can't upvote yet, but I'll come back here once I can. – Laboratorio Cobotica Oct 12 at 7:51

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.