I’ve been writing lots of bash scripts lately, so I thought it would be a good idea to document a few of the little tricks I’ve been using.
Force Execution
First off, to make a script that has to be executed in bash:
This was needed for a script that makes uses of Bash syntax for `for` loop and some basic math, and I had a user reporting errors when they tried to do
sh script.sh
. `sh` ignores the opening `#!/bin/bash` line and tries to execute the script directly, and fails when it hits those lines.Then, to make a script that has to be sourced in the global environment (to set environment variables like `PATH` and `LD_LIBRARY_PATH` for the user).
replace `script.sh` with the name of the actual file.
URL Encoding Arguments
Then, to URL Encode a parameter in bash (I used this to encode a user provided git password into the url), use this function:
Then you can use it like so:
*yeah yeah, I know.. SSH keys are better… tell it to the users, not me*
GetOpt
Finally, using `getopt`. It’s a big tool, but the basics of using it:
Important bits:
- the `getopts` line: Include each character recognized as a flag, and following it with a `:` if it requires an argument.
- Then include a case for each one in the big switch.. use `$(OPTARG)` to get the argument, if it’s needed.
Makes argument parsing simple in bash scripts simple… Also define a `usage` function to spew out the supported options, and you’re golden.