This page (http://www.oase-shareware.org/shell/shelltips.html) contains various shell tips & tricks. If you like, you can submit a new entry of your own.
Back to Heiner's SHELLdorado
|
"comment out" code blocks
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
One line of shell code can be "commented out" using the
"#" character. Sometimes however it would be nice to "comment out"
more than one line of code, like the C "/* */" comments.
One way to comment out multiple lines is this:
: '
,,,,,,
'
After the ":" command (that returns "true") the rest of the code
is a large string constant enclosed within 'single quotes'.
Of course this works only if the code "commented-out" does
not contain single quotes.
|
||
|
Providing default file name arguments to scripts
|
||
|---|---|---|
| Level: Intermediate | Submitted by: ??? |
URL:
none
|
If a shell script frequently works with files of a special type (i.e. "*.txt")
a script may use all files of this type in the current directory as default
if no file name is specified.
Example:
# changetextfiles
...
# If no arguments are specified, use all files matching "*.txt"
[ $# -lt 1 ] && set -- *.txt
...
|
||
|
Setting default values for variables
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
In shell scripts it's often useful to
provide default values for script variables, i.e.
if [ -z "$Host" ]
then
Host=`uname -n`
fi
For this kind of assignment the shell
has a shorthand:
: ${Host:=`uname -n`}
This means: if the variable "Host" is
not already set, execute the command
"uname -n" and set the variable to
the returned value.
|
||
|
Determine where a command is
|
||
|---|---|---|
| Level: Beginner | Submitted by: ??? |
URL:
none
|
The command "type" may be used to find out,
which command the shell executes.
Example:
$ type ls
/usr/bin/ls
$ type l
l is an alias for 'ls -l'
|
||
|
Using "here-documents" instead of multiple "echo"
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
Multiple "echo" commands may be replaced by a "here-document".
This makes the script faster and easier to read.
Example:
echo "Please enter your choice:"
echo "1 - list current directory"
echo "2 - list current users"
echo "3 - log off"
may be replaced with
cat <<!
Please enter your choice
1 - list current directory
2 - list current users
3 - log off
!
|
||
|
Indenting lines
|
||
|---|---|---|
| Level: Intermediate | Submitted by: ??? |
URL:
none
|
To indent all input lines with four blanks use
sed 's/^/ /'
This substitutes the "start-of-line" marker "^" with four spaces.
Since the marker will not disappear, the input
this is
a text
will be rewritten as
____this is
____a text
(The "underscore" character "_" in this example will be a non-visible
space character)
|
||
|
Suspending and resuming a command
|
||
|---|---|---|
| Level: Beginner | Submitted by: ??? |
URL:
none
|
If you did i.e. a "telnet" to another host, but want to do
a "ls -l" on the current host, you do not have to close the
"telnet" session.
Just type "^Z" (control-z) to suspend the current telnet session.
The command is then waiting for you to resume. In this time
you get a shell prompt and can issue any command.
If you are ready to continue, you can resume the "telnet" session
with the command "fg %1" ("foreground: the first command waiting").
If you want to run the command in the background, you could
issue a "bg %1" ("background: first command waiting"), too.
The command "jobs" lists all commands waiting.
|
||
|
"Normalize" input field separators
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
Script programmers sometimes have to process input that consists
of fields separated by whitespace, i.e.
field1 field 2 <TAB> <TAB> field3
This input has the disadvantage that it uses different combinations
of blank and TAB characters as input, and is hard to process using
"cut" and "sort", because these commands expect exactly one
field separator character.
The following "sed" line "normalizes" this input replacing each
sequence of two or more whitespace characters with exactly one
<TAB> character:
sed 's/ [ <TAB>][ <TAB>]*/<TAB>/g'
Substitute the five characters "<TAB>" with a "real" TAB character
(ASCII 9).
Further processing can be done using this <TAB> character
as field separator.
|
||
|
Include the current directory within your prompt
|
||
|---|---|---|
| Level: Beginner | Submitted by: ??? |
URL:
none
|
To include the current directory within the prompt, include
the following line into your $HOME/.kshrc (KSH) or $HOME/.bashrc
(BASH):
PS1='$PWD $'
export PS1
|
||
|
Case-insensitive pattern matching
|
||
|---|---|---|
| Level: Intermediate | Submitted by: ??? |
URL:
none
|
Some commands do not have a way to match text without considering
the character case, i.e. "awk":
awk '/abc/ { print $1 }'
will find lines containing "abc" but not "ABC" or "aBc". (Of course
in this case you could use "grep -i", but there are situations you
cannot use "grep").
With a little typing you can make this pattern case-insensitive:
awk '/[aA][bB][cC]/ { print $1 }'
This matches all combinations of "abc" with any character case.
You can always rewrite a constant expression like /pattern/
like this: /[pP][aA][tT][tT][eE][rR][nN]/. Just replace
each character "c" with the expression "[cC]" meaning:
either a small "c" or a upper-case "C"
|
||
|
Script debugging settings
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
Most shell script programmers know the command
set -vx
to print each script command before execution. Sometimes
the following flags are useful, too:
set -e # terminate the script at first error
set -u # unset variables are fatal errors
|
||
|
Convert "relative" in "absolute" path name
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
In shell scripts it is often necessary to convert a
relative path name, i.e. "../usr/../lib/somefile" to
an absolute path name starting with a slash "/", i.e.
"/lib/somefile". The following code fragment does exactly this:
D=`dirname "$relpath"`
B=`basename "$relpath"`
abspath="`cd \"$D\" 2>/dev/null && pwd || echo \"$D\"`/$B"
|
||
|
Find user's name
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: Acrosser@pcez.com |
URL:
http://across.hypermart.net
|
The full name of each user is available in the /etc/passwd file. If you
would like to use the full name in your script instead of $LOGNAME,
which simply returns the user's login name, you can declare the following
variable in your script:
fullname=`grep $LOGNAME /etc/passwd | cut -f 5 -d :`
If you only want the first name, you would declare this variable:
firstname=`grep $LOGNAME /etc/passwd | cut -f 5 -d : | cut -f 1 -d " "`
|
||
|
Positioning the cursor from within shell scripts
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ??? |
URL:
none
|
[This tip was first published within the SHELLdorado Newsletter 1/99]
For some shell scripts it would be desirable, if the script
could position the cursor to arbitrary (row, column) pairs
(i.e. to display a status line, ...)
The following shell function uses the "tput" command to
move the cursor to the specified (row, column) position:
# move cursor to row $1, col $2 (both starting with zero)
# usage: writeyx message rowno colno
writeyx () {
tput cup $2 $3
echo "$1"
}
Example usage:
clear # clear the screen
writeyx "This is a centered message" 11 26
writeyx "press any key to continue..." 22 0
read dummy
The "tput" comm!
and looks up the escape command sequence for
a feature needed for the current terminal. You can use it
for other terminal related things, too:
tput smso # "start mode shift out": usually
# reverse
echo "This is printed reverse"
tput rmso # "reset mode shift out"
All available capability names are listed on the terminfo(5)
manual page.
Portability:
The "tput" command is available with the "terminfo"
terminal information database
|
||
|
How to set the title of a XTERM window
|
||
|---|---|---|
| Level: Beginner | Submitted by: ??? |
URL:
none
|
[This tip was first published in the SHELLdorado Newsletter 1/99]
The title of a XTERM window can be set using the following
escape sequence:
ESC ] 0 ; title ^G
Example:
echo "^[]0;This is a title^G"
Enter the escape character (the first character of the
string) as CTRL-V ESC. On the screen you will see "^[". The
last character is entered as CTRL-V CTRL-G.
|
||
|
cleaning up tmp files.
|
||
|---|---|---|
| Level: Script Programmer | Submitted by: ericj@monkey.org |
URL:
none
|
I've seen too many scripts using massive number of tmp files, which is wrong in its self.
But not only that, people tend to clean them up one at a time in a fashion such as
if [ -a ${tmpFile} ]; then
rm ${tmpFile};
fi
This, when you use up to 10 or even 5 tmp files gets nasty. A quicker way of cleaning
up such tmp files is to use a simple loop, I even perfer to use array's which are
availible in Korn shell. Here is an example.
clean()
{
tmpfiles[0]=${temp1}
tmpfiles[1]=${temp2}
for file in ${tmpfiles[*]}
do
if [ -a ${file} ]; then
rm ${file}
fi
done
This way, as you accumulate more and more tmp files, you need only to add
one line to get it cleaned up.
|
||