-= BASH Notes
+= Bash Notes
== basename
Don't use `basename`, use:
-[,shell]
+[,bash]
----
- file=${path##*/}
+file=${path##*/}
----
== dirname
Don't use `dirname`, use:
-[,shell]
+[,bash]
----
- dir=${path%/*}
+dir=${path%/*}
----
== shopt
If you set `shopt` in a function, reset to its default state with `trap`:
-[,shell]
+[,bash]
----
func() {
trap "$(shopt -p globstar)" RETURN
Instead of:
-[,shell]
+[,bash]
----
func() {
for file in $(find /usr/lib* -type f -name 'lib*.a' -print0 ); do
use:
-[,shell]
+[,bash]
----
func() {
trap "$(shopt -p nullglob globstar)" RETURN
Or collect the filenames in an array, if you need them more than once:
-[,shell]
+[,bash]
----
func() {
trap "$(shopt -p globstar)" RETURN
Or, if you really want to use `find`, use `-print0` and an array:
-[,shell]
+[,bash]
----
func() {
mapfile -t -d '' filenames < <(find /usr/lib* -type f -name 'lib*.a' -print0)
or:
-[,shell]
+[,bash]
----
func() {
find /usr/lib* -type f -name 'lib*.a' -print0 | while read -r -d '' file; do
or
-[,shell]
+[,bash]
----
func() {
while read -r -d '' file; do
Instead of:
-[,shell]
+[,bash]
----
func() {
other-cmd $(for k in "$@"; do echo "prefix-$k"; done)
do
-[,shell]
+[,bash]
----
func() {
other-cmd "${@/#/prefix-}"
or suffix:
-[,shell]
+[,bash]
----
func() {
other-cmd "${@/%/-suffix}"
Here we have an associate array `_drivers`, where we want to print the keys separated by ',':
-[,shell]
+[,bash]
----
- if [[ ${!_drivers[*]} ]]; then
- echo "rd.driver.pre=$(IFS=, ;echo "${!_drivers[*]}")" > "${initdir}"/etc/cmdline.d/00-watchdog.conf
- fi
+if [[ ${!_drivers[*]} ]]; then
+ echo "rd.driver.pre=$(IFS=, ;echo "${!_drivers[*]}")" > "${initdir}"/etc/cmdline.d/00-watchdog.conf
+fi
----
== Optional parameters to commands
If you want to call a command `cmd` with an option, if a variable is set, rather than doing:
-[,shell]
+[,bash]
----
func() {
local param="$1"
do it like this:
-[,shell]
+[,bash]
----
func() {
local param="$1"
If you want to specify the option even with an empty string do this:
-[,shell]
+[,bash]
----
func() {
local -a special_params
Or more simple, if you only have to set an option:
-[,shell]
+[,bash]
----
func() {
if [[ ${1+_} ]]; then