Table of Contents

bash

bash (Bourne-Again) is a shell.

Configuration files

Functions

You can define functions in a bash script like so:

hello()
{
	echo 'Hello, world'
}

And call it with hello. Be careful that it doesn't conflict with another program! (prefix it with something, just in case) You can pass arguments to a function just like a shell script with hello arg1 arg2. These are available as expected: $1 and $2 respectively.

In bash, functions can't have prototypes. So, for readability, you can structure your program like this:

#!/bin/bash
 
main() {
	hello
	goodbye
}
 
hello() {
}
 
goodbye() {
}
 
main "$@"

The last line actually begins execution of the script from the main function while passing it the script's arguments.

Parameter expansion

Taken from Wooledge bashFAQ: parameter result ———– ——————————————————– $file /usr/share/java-1.4.2-sun/demo/applets/Clock/Clock.class ${file#/} usr/share/java-1.4.2-sun/demo/applets/Clock/Clock.class ${file##/} Clock.class ${file%%/} ${file%/} /usr/share/java-1.4.2-sun/demo/applets/Clock

${file%.mp3} filename without mp3 extension

More examples:

FullPath=/path/to/name4afile-009.ext     # result:   #   /path/to/name4afile-009.ext
Filename=${FullPath##*/}                             #   name4afile-009.ext
PathPref=${FullPath%"$Filename"}                     #   /path/to/
FileStub=${Filename%.*}                              #   name4afile-009
FileExt=${Filename#"$FileStub"}                      #   .ext
FnumPossLeading0s=${FileStub##*[![:digit:]]}         #   009
FnumOnlyLeading0s=${FnumPossLeading0s%%[!0]*}        #   00
FileNumber=${FnumPossLeading0s#"$FnumOnlyLeading0s"} #   9
NextNumber=$(( FileNumber + 1 ))                     #   10
NextNumberWithLeading0s=$(printf "%0${#FnumPossLeading0s}d" "$NextNumber")
                                                     #   010
FileStubNoNum=${FileStub%"$FnumPossLeading0s"}       #   name4afile-
NewFullPath=${PathPref}New_${FileStubNoNum}${NextNumberWithLeading0s}${FileExt}
# Final result is:           #   /path/to/New_name4afile-010.ext

See also


Afterwards, you can delve into http://mywiki.wooledge.org/BashGuide for a more complete guide (also shell scripting). The http://mywiki.wooledge.org/BashFAQ and http://mywiki.wooledge.org/BashPitfalls are especially useful

https://guide.bash.academy/inception/ → WIP guide on bash and shell scripting