Bash history inconsistent text - oh-my-zsh

When in terminal and pressing the up arrow to go through my bash history the line will often get messed up. This is especially true when the history is multiline or has special characters in it.
It's difficult to provide and example, but if my history is:
1 echo hello world
2 export foo=bar
3 cat /my/file.txt
Then pushing up will give me first cat /my/file.txt then export foo=bar and then it may break and do something like execho hello world. Going back down then will stay broken.
My bash prompt is:
echo $PS1
%(?:%{%}➜ :%{%}➜ ) %{$fg[cyan]%}%c%{$reset_color%} $(git_prompt_info)
I'm assuming there's an issue with my bash prompt, but I would hate to change it as I'm accustomed to the look/style. Would hopefully be able to find a solution.

Related

oh-my-zsh cursor up before program has finished vs after, how to make them behave consistently

I've noticed that if I press up arrow at a prompt then I get the previous command and up again gets me the command before that.
Whereas if I press up arrow before the previous program has completed then instead I get the previous command displayed, the cursor is at the end of the line, but oh-my-zsh is now in "search for lines that start with ... " mode meaning I can't press up to get the previous command.
I'm sure this behavior is well known and expected but just in case you don't get it you can repo it like this
Type ls return
Type sleep 3 return
wait 3 seconds for prompt to appear
press ⬆ (should show sleep 3)
press ⬆ again (should show ls)
press return (to run ls)
Type sleep 3 return ⬆ (press the up arrow before the 3 seconds elapses)
It should now be showing sleep 3
Press ⬆
it will still be showing sleep 3 but it want it to be showing ls. Instead it is in "search for commands that start with sleep 3 mode instead of just go to previous command mode.
To make try to clear in both cases these are the steps
lsreturn
sleep 3return
⬆
⬆
But they end up with different results depending on if step3 happens before or after step2 finishes.
Note I saw this Q&A: https://unix.stackexchange.com/questions/324623/how-to-make-oh-my-zsh-history-behavior-similar-to-bashs
But that doesn't seem to be what I'm looking for. I like oh-my-zsh's partial line + up = search for lines that start with the partial. What I'm trying to fix is that if I press up on step 2 above it magically inserts a partial where as if I wait until step 2 finishes it doesn't.
How do I get oh-my-zsh to be consistent here so that a premature up arrow behaves the same as a normal up arrow?
I'm surprised this question isn't common. It's seriously infuriating to have the terminal act inconsistently. I'd except most devs using oh-my-zsh to run into this issue all the time and be massively frustrated.
The example above with sleep 3 is only to make it easy to show the problem. In actual usage the problem happens frequently even with short lived commands. I type say git status return git commit somefile -m "short comment" return ⬆⬆ expecting to see "git status". 66% of the time I get git status and the other 34% I get `git commit somefile -m "short comment" and pressing ⬆ again just blinks the cursor and I have to press Ctrl-C to break out of zsh's partial complete mode.
The fact that this does not seem to be a common complaint for oh-my-zsh makes me wonder if I have something setup wrong.
To make it clearer run zsh without oh-my-zsh.
zsh -d -f
autoload -U up-line-or-beginning-search
zle -N up-line-or-beginning-search
bindkey "^[[A" up-line-or-beginning-search
Now try the steps above. You'll get consistent behavior.
This might be an overkill solution but, following this guide you can see that you can bind new actions to the up/down arrow key. So if you add:
bindkey "^[[A" up-line-or-beginning-search # Up
bindkey "^[[B" down-line-or-beginning-search # Down
to your ~/.zshrc, it should remove the functionality you talked about. I managed to get it to work while still maintaining regular search capabilities but this is not thoroughly tested and should probably be used with care.

while [[ condition ]] stalls on loop exit

I have a problem with ksh in that a while loop is failing to obey the "while" condition. I should add now that this is ksh88 on my client's Solaris box. (That's a separate problem that can't be addressed in this forum. ;) I have seen Lance's question and some similar but none that I have found seem to address this. (Disclaimer: NO I haven't looked at every ksh question in this forum)
Here's a very cut down piece of code that replicates the problem:
1 #!/usr/bin/ksh
2 #
3 go=1
4 set -x
5 tail -0f loop-test.txt | while [[ $go -eq 1 ]]
6 do
7 read lbuff
8 set $lbuff
9 nwords=$#
10 printf "Line has %d words <%s>\n" $nwords "${lbuff}"
11 if [[ "${lbuff}" = "0" ]]
12 then
13 printf "Line consists of %s; time to absquatulate\n" $lbuff
14 go=0 # Violate the WHILE condition to get out of loop
15 fi
16 done
17 printf "\nLooks like I've fallen out of the loop\n"
18 exit 0
The way I test this is:
Run loop-test.sh in background mode
In a different window I run commands like "echo some nonsense >>loop_test.txt" (w/o the quotes, of course)
When I wish to exit, I type "echo 0 >>loop-test.txt"
What happens? It indeed sets go=0 and displays the line:
Line consists of 0; time to absquatulate
but does not exit the loop. To break out I append one more line to the txt file. The loop does NOT process that line and just falls out of the loop, issuing that "fallen out" message before exiting.
What's going on with this? I don't want to use "break" because in the actual script, the loop is monitoring the log of a database engine and the flag is set when it sees messages that the engine is shutting down. The actual script must still process those final lines before exiting.
Open to ideas, anyone?
Thanks much!
-- J.
OK, that flopped pretty quick. After reading a few other posts, I found an answer given by dogbane that sidesteps my entire pipe-to-while scheme. His is the second answer to a question (from 2013) where I see neeraj is using the same scheme I'm using.
What was wrong? The pipe-to-while has always worked for input that will end, like a file or a command with a distinct end to its output. However, from a tail command, there is no distinct EOF. Hence, the while-in-a-subshell doesn't know when to terminate.
Dogbane's solution: Don't use a pipe. Applying his logic to my situation, the basic loop is:
while read line
do
# put loop body here
done < <(tail -0f ${logfile})
No subshell, no problem.
Caveat about that syntax: There must be a space between the two < operators; otherwise it looks like a HEREIS document with bad syntax.
Er, one more catch: The syntax did not work in ksh, not even in the mksh (under cygwin) which emulates ksh93. But it did work in bash. So my boss is gonna have a good laugh at me, 'cause he knows I dislike bash.
So thanks MUCH, dogbane.
-- J
After articulating the problem and sleeping on it, the reason for the described behavior came to me: After setting go=0, the control flow of the loop still depends on another line of data coming in from STDIN via that pipe.
And now that I have realized the cause of the weirdness, I can speculate on an alternative way of reading from the stream. For the moment I am thinking of the following solution:
Open the input file as STDIN (Need to research the exec syntax for that)
When the condition occurs, close STDIN (Again, need to research the syntax for that)
It should then be safe to use the more intuitive:while read lbuffat the top of the loop.
I'll test this out today and post the result. I'd hope someone else benefit from the method (if it works).

Tail and grep combo to show text in a multi line pattern

Not sure if you can do this through tail and grep. Lets say I have a log file that I would like to tail. It spits out quite a bit of information when in debug mode. I want to grep for information pertaining to only my module, and the module name is in the log like so:
/*** Module Name | 2014.01.29 14:58:01
a multi line
dump of some stacks
or whatever
**/
/*** Some Other Module Name | 2014.01.29 14:58:01
this should show up in the grep
**/
So as you can imagine, the number of lines that would be spit out pertaining to "Module Name" could be 2, or 50 until the end pattern appears (**/)
From your description, it seems like this should work:
tail -f log | awk '/^\/\*\*\* Module Name/,/^\*\*\//'
but be wary of buffering issues. (Lines printed to the file will very likely see high latency before actually being printed.)
I think you will have to install pcregrep for this. Then this will work:
tail -f logfile | pcregrep -M "^\/\*\*\* Some Other Module Name \|.*(\n|.)*?^\*\*/$"
This worked in testing, but for some reason, I had to append your example text to the log file over 100 times before output started showing up. However, all of the "Some other Module Name" data that was written to the log file as soon as this line was invoked was eventually printed to stdout.

Nano hacks: most useful tiny programs you've coded or come across

It's the first great virtue of programmers. All of us have, at one time or another automated a task with a bit of throw-away code. Sometimes it takes a couple seconds tapping out a one-liner, sometimes we spend an exorbitant amount of time automating away a two-second task and then never use it again.
What tiny hack have you found useful enough to reuse? To make go so far as to make an alias for?
Note: before answering, please check to make sure it's not already on favourite command-line tricks using BASH or perl/ruby one-liner questions.
i found this on dotfiles.org just today. it's very simple, but clever. i felt stupid for not having thought of it myself.
###
### Handy Extract Program
###
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xvjf $1 ;;
*.tar.gz) tar xvzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xvf $1 ;;
*.tbz2) tar xvjf $1 ;;
*.tgz) tar xvzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted via >extract<" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
Here's a filter that puts commas in the middle of any large numbers in standard input.
$ cat ~/bin/comma
#!/usr/bin/perl -p
s/(\d{4,})/commify($1)/ge;
sub commify {
local $_ = shift;
1 while s/^([ -+]?\d+)(\d{3})/$1,$2/;
return $_;
}
I usually wind up using it for long output lists of big numbers, and I tire of counting decimal places. Now instead of seeing
-rw-r--r-- 1 alester alester 2244487404 Oct 6 15:38 listdetail.sql
I can run that as ls -l | comma and see
-rw-r--r-- 1 alester alester 2,244,487,404 Oct 6 15:38 listdetail.sql
This script saved my career!
Quite a few years ago, i was working remotely on a client database. I updated a shipment to change its status. But I forgot the where clause.
I'll never forget the feeling in the pit of my stomach when I saw (6834 rows affected). I basically spent the entire night going through event logs and figuring out the proper status on all those shipments. Crap!
So I wrote a script (originally in awk) that would start a transaction for any updates, and check the rows affected before committing. This prevented any surprises.
So now I never do updates from command line without going through a script like this. Here it is (now in Python):
import sys
import subprocess as sp
pgm = "isql"
if len(sys.argv) == 1:
print "Usage: \nsql sql-string [rows-affected]"
sys.exit()
sql_str = sys.argv[1].upper()
max_rows_affected = 3
if len(sys.argv) > 2:
max_rows_affected = int(sys.argv[2])
if sql_str.startswith("UPDATE"):
sql_str = "BEGIN TRANSACTION\\n" + sql_str
p1 = sp.Popen([pgm, sql_str],stdout=sp.PIPE,
shell=True)
(stdout, stderr) = p1.communicate()
print stdout
# example -> (33 rows affected)
affected = stdout.splitlines()[-1]
affected = affected.split()[0].lstrip('(')
num_affected = int(affected)
if num_affected > max_rows_affected:
print "WARNING! ", num_affected,"rows were affected, rolling back..."
sql_str = "ROLLBACK TRANSACTION"
ret_code = sp.call([pgm, sql_str], shell=True)
else:
sql_str = "COMMIT TRANSACTION"
ret_code = sp.call([pgm, sql_str], shell=True)
else:
ret_code = sp.call([pgm, sql_str], shell=True)
I use this script under assorted linuxes to check whether a directory copy between machines (or to CD/DVD) worked or whether copying (e.g. ext3 utf8 filenames -> fusebl
k) has mangled special characters in the filenames.
#!/bin/bash
## dsum Do checksums recursively over a directory.
## Typical usage: dsum <directory> > outfile
export LC_ALL=C # Optional - use sort order across different locales
if [ $# != 1 ]; then echo "Usage: ${0/*\//} <directory>" 1>&2; exit; fi
cd $1 1>&2 || exit
#findargs=-follow # Uncomment to follow symbolic links
find . $findargs -type f | sort | xargs -d'\n' cksum
Sorry, don't have the exact code handy, but I coded a regular expression for searching source code in VS.Net that allowed me to search anything not in comments. It came in very useful in a particular project I was working on, where people insisted that commenting out code was good practice, in case you wanted to go back and see what the code used to do.
I have two ruby scripts that I modify regularly to download all of various webcomics. Extremely handy! Note: They require wget, so probably linux. Note2: read these before you try them, they need a little bit of modification for each site.
Date based downloader:
#!/usr/bin/ruby -w
Day = 60 * 60 * 24
Fromat = "hjlsdahjsd/comics/st%Y%m%d.gif"
t = Time.local(2005, 2, 5)
MWF = [1,3,5]
until t == Time.local(2007, 7, 9)
if MWF.include? t.wday
`wget #{t.strftime(Fromat)}`
sleep 3
end
t += Day
end
Or you can use the number based one:
#!/usr/bin/ruby -w
Fromat = "http://fdsafdsa/comics/%08d.gif"
1.upto(986) do |i|
`wget #{sprintf(Fromat, i)}`
sleep 1
end
Instead of having to repeatedly open files in SQL Query Analyser and run them, I found the syntax needed to make a batch file, and could then run 100 at once. Oh the sweet sweet joy! I've used this ever since.
isqlw -S servername -d dbname -E -i F:\blah\whatever.sql -o F:\results.txt
This goes back to my COBOL days but I had two generic COBOL programs, one batch and one online (mainframe folks will know what these are). They were shells of a program that could take any set of parameters and/or files and be run, batch or executed in an IMS test region. I had them set up so that depending on the parameters I could access files, databases(DB2 or IMS DB) and or just manipulate working storage or whatever.
It was great because I could test that date function without guessing or test why there was truncation or why there was a database ABEND. The programs grew in size as time went on to include all sorts of tests and become a staple of the development group. Everyone knew where the code resided and included them in their unit testing as well. Those programs got so large (most of the code were commented out tests) and it was all contributed by people through the years. They saved so much time and settled so many disagreements!
I coded a Perl script to map dependencies, without going into an endless loop, For a legacy C program I inherited .... that also had a diamond dependency problem.
I wrote small program that e-mailed me when I received e-mails from friends, on an rarely used e-mail account.
I wrote another small program that sent me text messages if my home IP changes.
To name a few.
Years ago I built a suite of applications on a custom web application platform in PERL.
One cool feature was to convert SQL query strings into human readable sentences that described what the results were.
The code was relatively short but the end effect was nice.
I've got a little app that you run and it dumps a GUID into the clipboard. You can run it /noui or not. With UI, its a single button that drops a new GUID every time you click it. Without it drops a new one and then exits.
I mostly use it from within VS. I have it as an external app and mapped to a shortcut. I'm writing an app that relies heavily on xaml and guids, so I always find I need to paste a new guid into xaml...
Any time I write a clever list comprehension or use of map/reduce in python. There was one like this:
if reduce(lambda x, c: locks[x] and c, locknames, True):
print "Sub-threads terminated!"
The reason I remember that is that I came up with it myself, then saw the exact same code on somebody else's website. Now-adays it'd probably be done like:
if all(map(lambda z: locks[z], locknames)):
print "ya trik"
I've got 20 or 30 of these things lying around because once I coded up the framework for my standard console app in windows I can pretty much drop in any logic I want, so I got a lot of these little things that solve specific problems.
I guess the ones I'm using a lot right now is a console app that takes stdin and colorizes the output based on xml profiles that match regular expressions to colors. I use it for watching my log files from builds. The other one is a command line launcher so I don't pollute my PATH env var and it would exceed the limit on some systems anyway, namely win2k.
I'm constantly connecting to various linux servers from my own desktop throughout my workday, so I created a few aliases that will launch an xterm on those machines and set the title, background color, and other tweaks:
alias x="xterm" # local
alias xd="ssh -Xf me#development_host xterm -bg aliceblue -ls -sb -bc -geometry 100x30 -title Development"
alias xp="ssh -Xf me#production_host xterm -bg thistle1 ..."
I have a bunch of servers I frequently connect to, as well, but they're all on my local network. This Ruby script prints out the command to create aliases for any machine with ssh open:
#!/usr/bin/env ruby
require 'rubygems'
require 'dnssd'
handle = DNSSD.browse('_ssh._tcp') do |reply|
print "alias #{reply.name}='ssh #{reply.name}.#{reply.domain}';"
end
sleep 1
handle.stop
Use it like this in your .bash_profile:
eval `ruby ~/.alias_shares`

What must I know to use GNU Screen properly? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I've just introduced a friend to GNU Screen and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent Screen utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?
It would be awesome.
I've been using Screen for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are:
^A ^W - window list, where am I
^A ^C - create new window
^A space - next window
^A p - previous window
^A ^A - switch to previous screen (toggle)
^A [0-9] - go to window [0-9]
^A esc - copy mode, which I use for scrollback
I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both ^Q and ^A ^Q to try to unlock it.
I couldn't get used to screen until I found a way to set a 'status bar' at the bottom of the screen that shows what 'tab' or 'virtual screen' you're on and which other ones there are. Here is my setup:
[roel#roel ~]$ cat .screenrc
# Here comes the pain...
caption always "%{=b dw}:%{-b dw}:%{=b dk}[ %{-b dw}%{-b dg}$USER%{-b dw}#%{-b dg}%H %{=b dk}] [ %= %?%{-b dg}%-Lw%?%{+b dk}(%{+b dw}%n:%t%{+b dk})%?(%u)%?%{-b dw}%?%{-b dg}%+Lw%? %{=b dk}]%{-b dw}:%{+b dw}:"
backtick 2 5 5 $HOME/scripts/meminfo
hardstatus alwayslastline "%{+b dw}:%{-b dw}:%{+b dk}[%{-b dg} %0C:%s%a %{=b dk}]-[ %{-b dw}Load%{+b dk}:%{-b dg}%l %{+b dk}] [%{-b dg}%2`%{+b dk}] %=[ %{-b dg}%1`%{=b dk} ]%{-b dw}:%{+b dw}:%<"
sorendition "-b dw"
[roel#roel ~]$ cat ~/scripts/meminfo
#!/bin/sh
RAM=`cat /proc/meminfo | grep "MemFree" | awk -F" " '{print $2}'`
SWAP=`cat /proc/meminfo | grep "SwapFree" | awk -F" " '{print $2}'`
echo -n "${RAM}kb/ram ${SWAP}kb/swap"
[roel#roel ~]$
Ctrl+A ? - show the help screen!
If your friend is in the habit of pressing ^A to get to the beginning of the line in Bash, he/she is in for some surprises, since ^A is the screen command key binding. Usually I end up with a frozen screen, possibly because of some random key I pressed after ^A :-)
In those cases I try
^A s and ^A q block/unblock terminal scrolling
to fix that. To go to the beginning of a line inside screen, the key sequence is ^A a.
You can remap the escape key from Ctrl + A to be another key of your choice, so if you do use it for something else, e.g. to go to the beginning of the line in bash, you just need to add a line to your ~/.screenrc file. To make it ^b or ^B, use:
escape ^bB
From the command line, use names sessions to keep multiple sessions under control. I use one session per task, each with multiple tabs:
screen -ls # Lists your current screen sessions
screen -S <name> # Creates a new screen session called name
screen -r <name> # Connects to the named screen sessions
When using screen you only need a few commands:
^A c Create a new shell
^A [0-9] Switch shell
^A k Kill the current shell
^A d Disconnect from screen
^A ? Show the help
An excellent quick reference can be found here. It is worth bookmarking.
Some tips for those sorta familiar with screen, but who tend to not remember things they read in the man page:
To change the name of a screen window is very easy: ctrl+A shift+A.
Did you miss the last message from screen? ctrl+a ctrl+m will show it again for you.
If you want to run something (like tailing a file) and have screen tell you when there's a change, use ctrl+A shift+m on the target window. Warning: it will let you know if anything changes.
Want to select window 15 directly? Try these in your .screenrc file:
bind ! select 11
bind # select 12
bind \# select 13
bind $ select 14
bind % select 15
bind \^ select 16
bind & select 17
bind * select 18
bind ( select 19
bind ) select 10
That assigns ctrl+a shift+0 through 9 for windows 10 through 19.
Ctrl+A is the base command
Ctrl+A N = go to the ***N***ext screen
Ctrl+A P = go to the ***P***revious screen
Ctrl+A C = ***C***reate new screen
Ctrl+A D = ***D***etach your screen
http://www.debian-administration.org/articles/34
I wrote that a couple of years ago, but it is still a good introduction that gets a lot of positive feedback.
I "must" add this: add
bind s
to your .screenrc, if You - like me - used to use split windows, as C-a S splits the actual window, but C-a s freezes it. So I just disabled the freeze shortcut.
Ctrl+a is a special key.
Ctrl+a d - [d]etach, leave programs (irssi?) in background, go home.
Ctrl+a c [c]reate a new window
Ctrl+a 0-9 switch between windows by number
screen -r - get back to detached session
That covers 90% of use cases. Do not try to show all the functionality at the single time.
Not really essential not solely related to screen, but enabling 256 colors in my terminal, GNU Screen and Vim improved my screen experience big time (especially since I code in Vim about 8h a day - there are some great eye-friendly colorschemes).
The first modification I make to .screenrc is to change the escape command. Not unlike many of you, I do not like the default Ctrl-A sequence because of its interference with that fundamental functionality in almost every other context. In my .screenrc file, I add:
escape `e
That's backtick-e.
This enables me to use the backtick as the escape key (e.g. to create a new screen, I press backtick-c, detach is backtick-d, backtick-? is help, backtick-backtick is previous screen, etc.). The only way it interferes (and I had to break myself of the habit) is using backtick on the command line to capture execution output, or pasting anything that contains a backtick. For the former, I've modified my habit by using the BASH $(command) convention. For the latter, I usually just pop open another xterm or detach from screen then paste the content containing the backtick. Finally, if I wish to insert a literal backtick, I simply press backtick-e.
There is some interesting work being done on getting a good GNU screen setup happening by default in the next version of Ubuntu Server, which includes using the bottom of the screen to show all the windows as well as other useful machine details (like number of updates available and whether the machine needs a reboot). You can probably grab their .screenrc and customise it to your needs.
The most useful commands I have in my .screenrc are the following:
shelltitle "$ |bash" # Make screen assign window titles automatically
hardstatus alwayslastline "%w" # Show all window titles at bottom line of term
This way I always know what windows are open, and what is running in them at the moment, too.
I use the following for ssh:
#!/bin/sh
# scr - Runs a command in a fresh screen
#
# Get the current directory and the name of command
wd=`pwd`
cmd=$1
shift
# We can tell if we are running inside screen by looking
# for the STY environment variable. If it is not set we
# only need to run the command, but if it is set then
# we need to use screen.
if [ -z "$STY" ]; then
$cmd $*
else
# Screen needs to change directory so that
# relative file names are resolved correctly.
screen -X chdir $wd
# Ask screen to run the command
if [ $cmd == "ssh" ]; then
screen -X screen -t ""${1##*#}"" $cmd $*
else
screen -X screen -t "$cmd $*" $cmd $*
fi
fi
Then I set the following bash aliases:
vim() {
scr vim $*
}
man() {
scr man $*
}
info() {
scr info $*
}
watch() {
scr watch $*
}
ssh() {
scr ssh $*
}
It opens a new screen for the above aliases and iff using ssh, it renames the screen title with the ssh hostname.
I like to set up a screen session with descriptive names for the windows. ^a A will let you give a name to the current window and ^a " will give you a list of your windows.
When done, detach the screen with ^a d and re-attach with screen -R
I like to use screen -d -RR to automatically create/attach to a given screen. I created bash functions to make it easier...
function mkscreen
{
local add=n
if [ "$1" == '-a' ]; then
add=y
shift;
fi
local name=$1;
shift;
local command="$*";
if [ -z "$name" -o -z "$command" ]; then
echo 'Usage: mkscreen [ -a ] name command
-a Add to .bashrc.' 1>&2;
return 1;
fi
if [ $add == y ]; then
echo "mkscreen $name $command" >> $HOME/.bashrc;
fi
alias $name="/usr/bin/screen -d -RR -S $name $command";
return 0;
}
function rmscreen
{
local delete=n
if [ "$1" == '-d' ]; then
delete=y
shift;
fi
local name=$1;
if [ -z "$name" ]; then
echo 'Usage: rmscreen [ -d ] name
-d Delete from .bashrc.' 1>&2;
return 1;
fi
if [ $delete == y ]; then
sed -i -r "/^mkscreen $name .*/d" $HOME/.bashrc;
fi
unalias $name;
return 0;
}
They create an alias to /usr/bin/screen -d -RR -S $name $command. For example, I like to use irssi in a screen session, so in my .bashrc (beneath those functions), I have:
mkscreen irc /usr/bin/irssi
Then I can just type irc in a terminal to get into irssi. If the screen 'irc' doesn't exist yet then it is created and /usr/bin/irssi is run from it (which connects automatically, of course). If it's already running then I just reattach to it, forcibly detaching any other instance that is already attached to it. It's quite nice.
Another example is creating temporary screen aliases for perldocs as I come across them:
mkscreen perlipc perldoc perlipc
perlipc # Start reading the perldoc, ^A d to detach.
...
# Later, when I'm done reading it, or at least finished
# with the alias, I remove it.
rmscreen perlipc
The -a option (must be first argument) appends the screen alias to .bashrc (so it's persistent) and -d removes it (these can potentially be destructive, so use at own risk). xD
Append:
Another bash-ism that I find convenient when working a lot with screen:
alias sls='/usr/bin/screen -ls'
That way you can list your screens with a lot fewer keystrokes. I don't know if sls collides with any existing utilities, but it didn't at the time on my system so I went for it.
^A A switches back to the screen you just came from.
Ctrl + A is a great special character for Unix people, but if you're using screen to talk to OpenVMS, then not being able to ^A is going to make you bald prematurely.
In VMS, if you're editing a DCL command prior to execution from the history buffer, Insert mode is off (it has to be for a few reasons I won't get into here) ... to turn it on so you don't over-type your command rather than space things out, you have to hit `^A.