UNIX Shell (POSIX, ksh)
Use the IFS shell variable to split a line into fields:
$ grep root /etc/passwd | IFS=: read user x1 uid gid x2 home shell $ print $uid $home
Note: The above commands will not give the desired output on a Bash environment.
To send all output (stdout and stderr) generated by a command to the same file use:
$ command >file 2>&1
To send all output (stdout and stderr) generated by a command to a file and to the terminal (stdout) use:
$ command 2>&1 | tee file
The following string substitution operators can be used:
${varname:-value} | Return value of varname if it exists and
it is not null; otherwise return value . |
${varname:=value} | Return value of varname if it exists and
it is not null; otherwise set varname to
value and return value . |
${varname:?message} | Return value of varname if it exists and
it is not null; otherwise print varname:
message and abort current command or script.
Default message is parameter null
or not set . |
${varname:+value} | Return value , if varname
exists and it is not null; otherwise return null. |
Note that if the colon (:
) is omitted, then only
existence test is done and varname
is not tested for
nullness.
Bash has more string substitution operators.
The following pattern-matching operators can be used:
${varname#pattern} | If pattern matches the beginning of
varname ’s value, delete the shortest part that
mathes and return the rest. |
${varname##pattern} | If pattern matches the beginning of
varname ’s value, delete the longest part that
mathes and return the rest. |
${varname%pattern} | If pattern matches the end of
varname ’s value, delete the shortest part that
mathes and return the rest. |
${varname%%pattern} | If pattern matches the end of
varname ’s value, delete the longest part that
mathes and return the rest. |
Examples:
$ var=variable $ print ${var#*a} riable $ print ${var##*a} ble $ print ${var%a*} vari $ print ${var%%a*} v
Use the command:
$ expr index string string2
to display the numerical position in
string
of first character in
string2
that matches.
$ expr substr string position length
to extract length
characters of substring from
string
starting at position
.
An
$ exec >filename
command redirects stdout to a designated file. This sends all subsequent command output that would normally go to stdout to that file. To resume output enter:
$ exec >/dev/tty