BashCookBook - henk52/knowledgesharing GitHub Wiki
Bash cook book
Introduction
References
get path to this script
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
Capture output of shell command in variable
OUTPUT=$(ls -1)
Functions
See: https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html
function hello {
echo Hello!
}
Parameters are accessible via $1, $2 etc
sudo Append text to a file
See: https://www.cyberciti.biz/faq/sudo-append-data-text-to-file-on-linux-unix-macos/
echo 'text' | sudo tee -a /path/to/file
Include timstamp as part of a file name
FILE_NAME="some_name_$(date +%Y%m%d%H%M%S)"
Auto complete
See:
-
https://askubuntu.com/questions/68175/how-to-create-script-with-auto-complete
-
http://www.gnu.org/software/bash/manual/bash.html#Programmable-Completion
-
https://github.com/scop/bash-completion/blob/master/README.md
-
compgen - Generate possible completion matches for word according to the options
-
compopt - Modify completion options for each name according to the options, or for the currently-executing completion if no names are supplied.
-
complete - Specify how arguments to each name should be completed.
The completion script:
# This script must be copied to(does not work):
# ~/.local/share/bash-completion/completions/
# Put it in: ~/.bash_completion
# our 'source' it from the ~/.bashrc
# Inspired from: https://askubuntu.com/questions/68175/how-to-create-script-with-auto-complete
_script()
{
# 'commandlist' is a command test_completion.sh recognizes and echo the list of commands
_script_commands=$(test_completion.sh commandlist)
local cur
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
COMPREPLY=( $(compgen -W "${_script_commands}" -- ${cur}) )
return 0
}
complete -o nospace -F _script test_completion.sh