GNU bash shell tips
The GNU bash manual is a great source of information on bash, as is Learning the bash Shell.
All examples written using GNU Bash version 4.0.33 on GNU/Linux. Most features will probably work in other versions, but minor differences might exist. Sample commands appear in examples prefixed by the prompt:
>
Why bash?
There is a positively huge number of unix shells out there. I wanted to focus on learning one shell really well, and the freedom to decide when to learn something else. The GPL, which is the licence under which bash is available, gives me that freedom, since it means bash, unlike commercial or restricted-use products, cannot suddenly go away, and will never take any "left turns" forcing me to switch.
Bash is a unix shell - and it's free, in both senses of the word. It is available on a wide variety of platforms. It has an Emacs mode, which makes many editing commands work similarly to GNU Emacs, and since that is my text editor of choice, bash was a natural choice for a shell (see gnu.org and Wikipedia).
Hello, World!
Write "Hello world!" to stdout:
#!/bin/bash echo 'Hello, World!'
Index
- Arithmetic
- Perform basic mathematical operations.
- Arrays
- The datastructure used to represent lists/collections.
- Exit status (and Command Grouping)
- Scripts give concise feedback about what they did by providing an integer status when they finish ("exit"). The exit status of a group of commands depends on the way the commands are grouped.
- File info
- Obtaining information about files in a script: File size, modification timestamp, etc.
- if command
- Condition the execution of a command on the succesful execution of another.
- Loops
- How to perform standard looping operations.
- Maps
- Maps, a.k.a. "Associative Arrays", store key-value pairs, where the key is a string rather than an integer.
- Outputting text (echo)
- Outputting text can be conveniently done using the echo command, which is available independently of the bash shell.
- Positional Parameters
- Arguments passed to a script when it is invoked are available as "positional parameters".
- Quoting Arguments
- Using quotes to get the desired degree of "verbatimicity" in your command arguments.
- Strings
- See Quoting Arguments: Shell Parameter Expansion and String Manipulation.
- Redirecting output
- How to provide standard input to commands, and how to direct output and error messages to the desired locations.
- Regular Expression Matching ( BASH_REMATCH)
- Match and extract parts of a string using regular expressions.
- Shell Configuration
- Customising how bash behaves using set, trap, etc.
- Variables
- How to store, reference, and generally work with values stored in variables.