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

See: https://stackoverflow.com/questions/4651437/how-do-i-set-a-variable-to-the-output-of-a-command-in-bash

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:

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