Bash Gems
10 Feb 2016The Bourne Again SHell is one of the most widely deployed shell for Linux that I use all the time. In today’s post, I’m going to collate a lot of the gems that I’d discovered in my travels of using this software.
Finding Help
Nothing can substitute the reference manual materials distributed with this software when it’s installed. At the console, you can read documentation in info format on bash using the following:
You’re able to deduce executing this command by doing some research at the console, by yourself. Using apropos
(which searches the manual pages) you can look for key words.
If you wanted to find any command that begins with the characters ‘ls’ in an attempt to find the command ls
, you can perform the following search:
On my system here, this function emits the following result:
We’re only interested in the first item there, but we’re given all of the options. We can now display the manual page with the following:
Variables
Variable creation is fairly straight forward:
Special variables exist to tell the developer a little bit about their environment:
Variable | Description |
---|---|
$? |
Return code from the last program that just ran |
$$ |
Currently executing script’s PID |
$# |
Number of arguments passed to this script (argc ) |
$@ |
All arguments passed to this script |
$1 $2 |
Each argument passed to the script ($3 , $4 , etc.) |
Functions
Control Flow Constructs
Redirection
Special file descriptors of 0
as /dev/stdin
, 1
as /dev/stdout
and 2
as /dev/stderr
.
From the redirections section in the bash manual:
Note that the order of redirections is significant. For example, the command
directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file
dirlist
, while the command
directs only the standard output to file
dirlist
, because the standard error was made a copy of the standard output before the standard output was redirected todirlist
.