diff --git a/src/tools/bash-memo/bash-memo.content.md b/src/tools/bash-memo/bash-memo.content.md index ef17e243..97d337d3 100644 --- a/src/tools/bash-memo/bash-memo.content.md +++ b/src/tools/bash-memo/bash-memo.content.md @@ -1,573 +1,556 @@ +**Bash** is the default shell on most Linux systems and the language of most glue scripts. This sheet covers the interactive shortcuts, the syntax you forget between scripts, and the safety flags worth putting at the top of every file. + ```bash -#!/bin/bash -############################################################################## -# SHORTCUTS and HISTORY -############################################################################## +#!/usr/bin/env bash +set -euo pipefail +``` -CTRL+A # move to beginning of line -CTRL+B # moves backward one character -CTRL+C # halts the current command -CTRL+D # deletes one character backward or logs out of current session, similar to exit -CTRL+E # moves to end of line -CTRL+F # moves forward one character -CTRL+G # aborts the current editing command and ring the terminal bell -CTRL+H # deletes one character under cursor (same as DELETE) -CTRL+J # same as RETURN -CTRL+K # deletes (kill) forward to end of line -CTRL+L # clears screen and redisplay the line -CTRL+M # same as RETURN -CTRL+N # next line in command history -CTRL+O # same as RETURN, then displays next line in history file -CTRL+P # previous line in command history -CTRL+Q # resumes suspended shell output -CTRL+R # searches backward -CTRL+S # searches forward or suspends shell output -CTRL+T # transposes two characters -CTRL+U # kills backward from point to the beginning of line -CTRL+V # makes the next character typed verbatim -CTRL+W # kills the word behind the cursor -CTRL+X # lists the possible filename completions of the current word -CTRL+Y # retrieves (yank) last item killed -CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background +## ⌨️ Keyboard Shortcuts -ALT+B # moves backward one word -ALT+D # deletes next word -ALT+F # moves forward one word -ALT+H # deletes one character backward -ALT+T # transposes two words -ALT+. # pastes last word from the last command. Pressing it repeatedly traverses through command history. -ALT+U # capitalizes every character from the current cursor position to the end of the word -ALT+L # uncapitalizes every character from the current cursor position to the end of the word -ALT+C # capitalizes the letter under the cursor. The cursor then moves to the end of the word. -ALT+R # reverts any changes to a command you’ve pulled from your history if you’ve edited it. -ALT+? # list possible completions to what is typed -ALT+^ # expand line to most recent match from history +| Keys | Does | +|---------------------|--------------------------------------------------| +| `Ctrl+A` / `Ctrl+E` | Jump to the start / end of the line | +| `Ctrl+B` / `Ctrl+F` | Back / forward one character | +| `Alt+B` / `Alt+F` | Back / forward one word | +| `Ctrl+U` / `Ctrl+K` | Cut to the start / end of the line | +| `Ctrl+W` | Cut the word before the cursor | +| `Alt+D` | Cut the word after the cursor | +| `Ctrl+Y` | Paste back what you last cut | +| `Ctrl+T` / `Alt+T` | Swap the last two characters / words | +| `Alt+.` | Insert the last argument of the previous command | +| `Ctrl+L` | Clear the screen | +| `Ctrl+R` | Search the history backwards | +| `Ctrl+G` | Abort the history search | +| `Ctrl+C` | Interrupt the running command | +| `Ctrl+D` | End of input — logs out of an empty prompt | +| `Ctrl+Z` | Suspend the running command | +| `Ctrl+S` / `Ctrl+Q` | Freeze / resume terminal output | +| `Alt+U` / `Alt+L` | Upper-case / lower-case to the end of the word | -CTRL+X then ( # start recording a keyboard macro -CTRL+X then ) # finish recording keyboard macro -CTRL+X then E # recall last recorded keyboard macro -CTRL+X then CTRL+E # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands -CTRL+A then D # logout from screen but don't kill it, if any command exist, it will continue +## 🕰 History -BACKSPACE # deletes one character backward -DELETE # deletes one character under cursor +```bash +# the last few hundred commands +history -history # shows command line history -!! # repeats the last command -! # refers to command line 'n' -! # refers to command starting with 'string' -esc :wq # exits and saves script +# run command number 42 +!42 -exit # logs out of current session +# run the last command again, or the last one starting with 'ssh' +!! +!ssh +# the last argument of the previous command — also Alt+. +!$ -############################################################################## -# BASH BASICS -############################################################################## +# every argument of the previous command +!* -env # displays all environment variables +# re-run the last command with a substitution +^old^new -echo $SHELL # displays the shell you're using -echo $BASH_VERSION # displays bash version +# forget a command you would rather not keep +history -d 42 -bash # if you want to use bash (type exit to go back to your previously opened shell) -whereis bash # locates the binary, source and manual-page for a command -which bash # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments) +# do not record commands that start with a space, and drop duplicates +export HISTCONTROL=ignoreboth +export HISTSIZE=10000 HISTFILESIZE=20000 +``` -clear # clears content on window (hide displayed lines) +## 📁 Files & Directories +```bash +# list: long, human sizes, hidden files, newest last +ls -lhAtr -############################################################################## -# FILE COMMANDS -############################################################################## +# tree view of a directory +tree -L 2 +# copy, move, delete +cp -r src/ dest/ +mv old new +rm -rf directory -ls # lists your files in current directory, ls to print files in a specific directory -ls -l # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified -ls -a # lists all files in 'long format', including hidden files (name beginning with '.') -ln -s # creates symbolic link to file -readlink # shows where a symbolic links points to -tree # show directories and subdirectories in easilly readable file tree -mc # terminal file explorer (alternative to ncdu) -touch # creates or updates (edit) your file -mktemp -t # make a temp file in /tmp/ which is deleted at next boot (-d to make directory) -cat # displays file raw content (will not be interpreted) -cat -n # shows number of lines -nl # shows number of lines in file -cat filename1 > filename2 # Copy filename1 to filename2 -cat filename1 >> filename2 # merge two files texts together -any_command > # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout) -more # shows the first part of a file (move with space and type q to quit) -head # outputs the first lines of file (default: 10 lines) -tail # outputs the last lines of file (useful with -f option) (default: 10 lines) -vim # opens a file in VIM (VI iMproved) text editor, will create it if it doesn't exist -mv # moves a file to destination, behavior will change based on 'dest' type (dir: file is placed into dir; file: file will replace dest (tip: useful for renaming)) -cp # copies a file -rm # removes a file -find . -name # searches for a file or a directory in the current directory and all its sub-directories by its name -diff # compares files, and shows where they differ -wc # tells you how many lines, words and characters there are in a file. Use -lwc (lines, word, character) to ouput only 1 of those informations -sort # sorts the contents of a text file line by line in alphabetical order, use -n for numeric sort and -r for reversing order. -sort -t -k # sorts the contents on specific sort key field starting from 1, using the field separator t. -rev # reverse string characters (hello becomes olleh) -chmod -options # lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID) -gzip # compresses files using gzip algorithm -gunzip # uncompresses files compressed by gzip -gzcat # lets you look at gzipped file without actually having to gunzip it -lpr # prints the file -lpq # checks out the printer queue -lprm # removes something from the printer queue -genscript # converts plain text files into postscript for printing and gives you some options for formatting -dvips # prints .dvi files (i.e. files produced by LaTeX) -grep # looks for the string in the files -grep -r # search recursively for pattern in directory -head -n file_name | tail +n # Print nth line from file. -head -y lines.txt | tail +x # want to display all the lines from x to y. This includes the xth and yth lines. +# create nested directories in one go +mkdir -p project/{src,test,docs} -sed 's///g' # replace pattern in file with replacement value to std output the character after s (/) is the delimeter -sed -i 's///g' # replace pattern in file with replacement value in place -echo "this" | sed 's/is/at/g' # replace pattern from input stream with replacement value +# symbolic and hard links +ln -s /path/to/target linkname +ln target hardlink -############################################################################## -# DIRECTORY COMMANDS -############################################################################## +# where is a file, and what is it? +find . -name '*.log' -mtime -7 +find . -type f -size +100M +locate nginx.conf +which python3 +type -a ls +file archive.bin +stat report.pdf +# disk usage: this directory, and the filesystem +du -sh * +du -h --max-depth=1 | sort -h +df -h -mkdir # makes a new directory -rmdir # remove an empty directory -rmdir -rf # remove a non-empty directory -mv # rename a directory from to -cd # changes to home -cd .. # changes to the parent directory -cd # changes directory -cp -r # copy into including sub-directories -pwd # tells you where you currently are -cd ~ # changes to home. -cd - # changes to previous working directory +# archives +tar czf backup.tar.gz directory/ +tar xzf backup.tar.gz +zip -r archive.zip directory/ +unzip archive.zip +``` -############################################################################## -# SSH, SYSTEM INFO & NETWORK COMMANDS -############################################################################## +## 🔎 Text & Search +```bash +# grep: recursive, line numbers, case-insensitive +grep -rni "pattern" . -ssh user@host # connects to host as user -ssh -p user@host # connects to host on specified port as user -ssh-copy-id user@host # adds your ssh key to host for user to enable a keyed or passwordless login +# only the matching part, or only the file names +grep -o 'v[0-9.]*' file +grep -rl "TODO" src/ -whoami # returns your username -su # switch to a different user -su - # switch to root, likely needs to be sudo su - -sudo # execute command as the root user -passwd # lets you change your password -quota -v # shows what your disk quota is -date # shows the current date and time -cal # shows the month's calendar -uptime # shows current uptime -w # displays whois online -finger # displays information about user -uname -a # shows kernel information -man # shows the manual for specified command -info # shows another documentation system for the specific command -help # shows documentation about built-in commands and functions -df # shows disk usage -du # shows the disk usage of the files and directories in filename (du -s give only a total) -resize2fs # ext2/ext3/ext4 file system resizer -last # lists your last logins -ps -u yourusername # lists your processes -kill # kills the processes with the ID you gave -killall # kill all processes with the name -top # displays your currently active processes -lsof # lists open files -bg # lists stopped or background jobs ; resume a stopped job in the background -fg # brings the most recent job in the foreground -fg # brings job to the foreground +# invert, count, context +grep -v "debug" app.log +grep -c "error" app.log +grep -B2 -A2 "exception" app.log -ping # pings host and outputs results -whois # gets whois information for domain -dig # gets DNS information for domain -dig -x # reverses lookup host -wget # downloads file -netstat # Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships +# head, tail, follow +head -20 file +tail -f /var/log/syslog -time # report time consumed by command execution +# columns, sorting, counting +cut -d',' -f1,3 data.csv +sort -u names.txt +sort -k2 -n scores.txt +uniq -c sorted.txt +wc -l file +# the classic: what are the top ten IPs in this log? +awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -############################################################################## -# VARIABLES -############################################################################## +# replace across many files +sed -i 's/old/new/g' *.conf +# translate or delete characters +tr 'a-z' 'A-Z' < file +tr -d '\r' < dos.txt > unix.txt -varname=value # defines a variable -varname=value command # defines a variable to be in the environment of a particular subprocess -echo $varname # checks a variable's value -echo $$ # prints process ID of the current shell -echo $! # prints process ID of the most recently invoked background job -echo $? # displays the exit status of the last command -read # reads a string from the input and assigns it to a variable -read -p "prompt" # same as above but outputs a prompt to ask user for value -column -t # display info in pretty columns (often used with pipe) -let = # performs mathematical calculation using operators like +, -, *, /, % -export VARNAME=value # defines an environment variable (will be available in subprocesses) -export -f # Exports function 'funcname' -export var1="var1 value" # Export and assign in the same statement -export # Copy Bash variable -declare -x # Copy Bash variable +# split a stream: to a file and onward down the pipe +command | tee output.log | grep error -array[0]=valA # how to define an array -array[1]=valB -array[2]=valC -array=([2]=valC [0]=valA [1]=valB) # another way -array=(valA valB valC) # and another +# build command lines from input +find . -name '*.py' | xargs wc -l +find . -name '*.tmp' -print0 | xargs -0 rm +``` -${array[i]} # displays array's value for this index. If no index is supplied, array element 0 is assumed -${#array[i]} # to find out the length of any element in the array -${#array[@]} # to find out how many values there are in the array +## 🖧 System & Network -declare -a # the variables are treated as arrays -declare -f # uses function names only -declare -F # displays function names without definitions -declare -i # the variables are treated as integers -declare -r # makes the variables read-only -declare -x # marks the variables for export via the environment -declare -l # uppercase values in the variable are converted to lowercase -declare -A # makes it an associative array +```bash +# who and where am I +whoami; hostname; uname -a; uptime -${varname:-word} # if varname exists and isn't null, return its value; otherwise return word -${varname:word} # if varname exists and isn't null, return its value; otherwise return word -${varname:=word} # if varname exists and isn't null, return its value; otherwise set it word and then return its value -${varname:?message} # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script -${varname:+word} # if varname exists and isn't null, return word; otherwise return null -${varname:offset:length} # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters +# processes +ps aux | grep nginx +pgrep -a node +top +htop -${variable#pattern} # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest -${variable##pattern} # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest -${variable%pattern} # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest -${variable%%pattern} # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest -${variable/pattern/string} # the longest match to pattern in variable is replaced by string. Only the first match is replaced -${variable//pattern/string} # the longest match to pattern in variable is replaced by string. All matches are replaced +# memory and load +free -h +vmstat 1 5 -${#varname} # returns the length of the value of the variable as a character string +# what is listening, and what has this file open +ss -tulpn +lsof -i :8080 +lsof /var/log/app.log -*(patternlist) # matches zero or more occurrences of the given patterns -+(patternlist) # matches one or more occurrences of the given patterns -?(patternlist) # matches zero or one occurrence of the given patterns -@(patternlist) # matches exactly one of the given patterns -!(patternlist) # matches anything except one of the given patterns +# connectivity +ping -c 4 example.com +traceroute example.com +dig example.com +short +ip addr show +curl -I https://example.com -$(UNIX command) # command substitution: runs the command and returns standard output +# transfer files +scp file user@host:/path/ +rsync -avz --progress src/ user@host:/dest/ -typeset -l # makes variable local - must be an interger +# remote shell, with a tunnel +ssh user@host +ssh -L 8080:localhost:80 user@host -############################################################################## -# FUNCTIONS -############################################################################## +# services and logs (systemd) +systemctl status nginx +journalctl -u nginx -f --since "1 hour ago" +``` +## 📦 Variables -# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth. -# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters. +```bash +# assignment: no spaces around the = +name="value" +# only for this one command +DEBUG=1 ./script.sh -function functname() { - shell commands -} +# export to child processes +export PATH="$HOME/bin:$PATH" -unset -f functname # deletes a function definition -declare -f # displays all defined functions in your login session +# read input from the user +read -p "Name: " name +read -rs -p "Password: " pass +# command substitution +today=$(date +%F) -############################################################################## -# FLOW CONTROLS -############################################################################## +# arithmetic +count=$(( count + 1 )) +let "n = 5 * 3" +# read-only and integer variables +declare -r VERSION=1.0 +declare -i counter=0 +``` -statement1 && statement2 # and operator -statement1 || statement2 # or operator +| Variable | Holds | +|----------------------------------|-------------------------------------------| +| `$0` | The name of the script | +| `$1` … `$9` | Positional arguments | +| `$#` | How many arguments were passed | +| `$@` | All arguments, each one quoted separately | +| `$*` | All arguments as a single word | +| `$?` | Exit status of the last command | +| `$$` | PID of the current shell | +| `$!` | PID of the last background job | +| `$_` | Last argument of the previous command | +| `$HOME` `$USER` `$PWD` `$OLDPWD` | The usual environment | +| `$RANDOM` | A random integer | +| `$LINENO` | The current line number — handy in traps | --a # and operator inside a test conditional expression --o # or operator inside a test conditional expression +## 🔤 Parameter Expansion -# STRINGS +| Expansion | Result | +|-------------------------|----------------------------------------------------------------------------| +| `${var:-default}` | `default` when `var` is unset or empty | +| `${var:=default}` | The same, and assigns it | +| `${var:?message}` | Abort with `message` when unset — great for required arguments | +| `${var:+value}` | `value` only when `var` **is** set | +| `${#var}` | The length of the value | +| `${var:offset:length}` | A substring | +| `${var#pattern}` | Strip the shortest match from the start | +| `${var##pattern}` | Strip the longest match from the start — `${path##*/}` is basename | +| `${var%pattern}` | Strip the shortest match from the end — `${file%.txt}` drops the extension | +| `${var%%pattern}` | Strip the longest match from the end | +| `${var/old/new}` | Replace the first match | +| `${var//old/new}` | Replace every match | +| `${var^^}` / `${var,,}` | Upper-case / lower-case the whole value | -str1 == str2 # str1 matches str2 -str1 != str2 # str1 does not match str2 -str1 < str2 # str1 is less than str2 (alphabetically) -str1 > str2 # str1 is greater than str2 (alphabetically) -str1 \> str2 # str1 is sorted after str2 -str1 \< str2 # str1 is sorted before str2 --n str1 # str1 is not null (has length greater than 0) --z str1 # str1 is null (has length 0) +```bash +path="/var/log/app.log" +echo "${path##*/}" # app.log +echo "${path%/*}" # /var/log +echo "${path%.log}" # /var/log/app +``` -# FILES +## 📚 Arrays --a file # file exists or its compilation is successful --d file # file exists and is a directory --e file # file exists; same -a --f file # file exists and is a regular file (i.e., not a directory or other special type of file) --r file # you have read permission --s file # file exists and is not empty --w file # your have write permission --x file # you have execute permission on file, or directory search permission if it is a directory --N file # file was modified since it was last read --O file # you own file --G file # file's group ID matches yours (or one of yours, if you are in multiple groups) -file1 -nt file2 # file1 is newer than file2 -file1 -ot file2 # file1 is older than file2 +```bash +# indexed arrays +fruits=(apple banana cherry) +fruits[3]="date" -# NUMBERS +echo "${fruits[1]}" # banana +echo "${fruits[@]}" # every element +echo "${#fruits[@]}" # how many elements +echo "${!fruits[@]}" # the indexes +echo "${fruits[@]:1:2}" # a slice --lt # less than --le # less than or equal --eq # equal --ge # greater than or equal --gt # greater than --ne # not equal +for fruit in "${fruits[@]}"; do + echo "$fruit" +done -if condition -then - statements -[elif condition - then statements...] -[else - statements] +# associative arrays (bash 4+) +declare -A color +color[apple]="red" +color[banana]="yellow" + +echo "${color[apple]}" +for key in "${!color[@]}"; do + echo "$key is ${color[$key]}" +done +``` + +## 🧪 Tests & Conditions + +Use `[[ ... ]]` in bash — it handles empty variables and patterns far better than the old `[ ... ]`. + +| Files | True when | +|----------------|-------------------------------------------| +| `-e file` | It exists | +| `-f file` | It exists and is a regular file | +| `-d file` | It exists and is a directory | +| `-L file` | It is a symbolic link | +| `-s file` | It exists and is not empty | +| `-r` `-w` `-x` | You can read / write / execute it | +| `-O file` | You own it | +| `f1 -nt f2` | `f1` is newer than `f2` (`-ot` for older) | + +| Strings | True when | +|----------------|-----------------------------------------------| +| `-z "$s"` | The string is empty | +| `-n "$s"` | The string is not empty | +| `"$a" == "$b"` | They are equal (`=` also works) | +| `"$a" != "$b"` | They differ | +| `"$a" < "$b"` | Sorts before, in the current locale | +| `"$s" == pre*` | Glob match — unquoted right-hand side | +| `"$s" =~ ^re$` | Regex match, captures land in `$BASH_REMATCH` | + +| Numbers | Meaning | +|---------|-----------------------| +| `-eq` | Equal | +| `-ne` | Not equal | +| `-lt` | Less than | +| `-le` | Less than or equal | +| `-gt` | Greater than | +| `-ge` | Greater than or equal | + +```bash +if [[ -f "$config" && -r "$config" ]]; then + echo "readable" +elif [[ -d "$config" ]]; then + echo "that is a directory" +else + echo "missing" fi -for x in {1..10} -do - statements -done +# arithmetic comparison reads more naturally in (( )) +if (( count > 10 )); then echo "plenty"; fi +``` -for name [in list] -do - statements that can use $name -done +## 🔀 Flow Control -for (( initialisation ; ending condition ; update )) -do - statements... -done +```bash +# for over a list, a glob, or a range +for name in alice bob; do echo "$name"; done +for f in *.log; do gzip "$f"; done +for i in {1..10}; do echo "$i"; done +for (( i = 0; i < 10; i++ )); do echo "$i"; done -case expression in - pattern1 ) - statements ;; - pattern2 ) - statements ;; +# while and until +while read -r line; do echo "$line"; done < input.txt +until ping -c1 host &>/dev/null; do sleep 5; done + +# case +case "$1" in + start) echo "starting" ;; + stop) echo "stopping" ;; + restart) echo "restarting" ;; + *) echo "usage: $0 {start|stop|restart}"; exit 1 ;; esac -select name [in list] -do - statements that can use $name +# select builds a numbered menu +select choice in build test deploy; do + echo "you picked $choice" + break done -while condition; do - statements -done +# loop control +continue # skip to the next iteration +break # leave the loop +``` -until condition; do - statements -done +## 🧰 Functions -############################################################################## -# COMMAND-LINE PROCESSING CYCLE -############################################################################## - - -# The default order for command lookup is functions, followed by built-ins, with scripts and executables last. -# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`. - -command # removes alias and function lookup. Only built-ins and commands found in the search path are executed -builtin # looks up only built-in commands, ignoring functions and commands found in PATH -enable # enables and disables shell built-ins - -eval # takes arguments and run them through the command-line processing steps all over again - - -############################################################################## -# INPUT/OUTPUT REDIRECTORS -############################################################################## - - -cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2 -< file # takes standard input from file -> file # directs standard output to file ->> file # directs standard output to file; append to file if it already exists ->|file # forces standard output to file even if noclobber is set -n>|file # forces output to file from file descriptor n even if noclobber is set -<> file # uses file as both standard input and standard output -n<>file # uses file as both input and output for file descriptor n -n>file # directs file descriptor n to file -n>file # directs file description n to file; append to file if it already exists -n>& # duplicates standard output to file descriptor n -n<& # duplicates standard input from file descriptor n -n>&m # file descriptor n is made to be a copy of the output file descriptor -n<&m # file descriptor n is made to be a copy of the input file descriptor -&>file # directs standard output and standard error to file -<&- # closes the standard input ->&- # closes the standard output -n>&- # closes the ouput from file descriptor n -n<&- # closes the input from file descriptor n - -|tee # output command to both terminal and a file (-a to append to file) - - -############################################################################## -# PROCESS HANDLING -############################################################################## - - -# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y. -# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal. -# Of course, to interrupt a job, type CTRL+C. - -myCommand & # runs job in the background and prompts back the shell - -jobs # lists all jobs (use with -l to see associated PID) - -fg # brings a background job into the foreground -fg %+ # brings most recently invoked background job -fg %- # brings second most recently invoked background job -fg %N # brings job number N -fg %string # brings job whose command begins with string -fg %?string # brings job whose command contains string - -kill -l # returns a list of all signals on the system, by name and number -kill PID # terminates process with specified PID -kill -s SIGKILL 4500 # sends a signal to force or terminate the process -kill -15 913 # Ending PID 913 process with signal 15 (TERM) -kill %1 # Where %1 is the number of job as read from 'jobs' command. - -ps # prints a line of information about the current running login shell and any processes running under it -ps -a # selects all processes with a tty except session leaders - -trap cmd sig1 sig2 # executes a command when a signal is received by the script -trap "" sig1 sig2 # ignores that signals -trap - sig1 sig2 # resets the action taken when the signal is received to the default - -disown # removes the process from the list of jobs - -wait # waits until all background jobs have finished -sleep # wait # of seconds before continuing - -pv # display progress bar for data handling commands. often used with pipe like |pv -yes # give yes response everytime an input is requested from script/process - - -############################################################################## -# TIPS & TRICKS -############################################################################## - - -# set an alias -cd; nano .bash_profile -> alias gentlenode='ssh admin@gentlenode.com -p 3404' # add your alias in .bash_profile - -# to quickly go to a specific directory -cd; nano .bashrc -> shopt -s cdable_vars -> export websites="/Users/mac/Documents/websites" - -source .bashrc -cd $websites - - -############################################################################## -# DEBUGGING SHELL PROGRAMS -############################################################################## - - -bash -n scriptname # don't run commands; check for syntax errors only -set -o noexec # alternative (set option in script) - -bash -v scriptname # echo commands before running them -set -o verbose # alternative (set option in script) - -bash -x scriptname # echo commands after command-line processing -set -o xtrace # alternative (set option in script) - -trap 'echo $varname' EXIT # useful when you want to print out the values of variables at the point that your script exits - -function errtrap { - es=$? - echo "ERROR line $1: Command exited with status $es." +```bash +greet() { + local name="${1:?name required}" + local greeting="${2:-Hello}" + echo "$greeting, $name!" + return 0 } -trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exits with non-zero status +greet "World" +greet "World" "Good morning" -function dbgtrap { - echo "badvar is $badvar" -} +# capture the output, and check the status +message=$(greet "World") +if ! greet; then echo "greet failed"; fi -trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script -# ...section of code in which the problem occurs... -trap - DEBUG # turn off the DEBUG trap +# make a function available to subshells +export -f greet +``` -function returntrap { - echo "A return occurred" -} +## ➡️ Redirection -trap returntrap RETURN # is executed each time a shell function or a script executed with the . or source commands finishes executing +| Syntax | Does | +|--------------------|--------------------------------------------| +| `> file` | Send stdout to a file, replacing it | +| `>> file` | Append stdout to a file | +| `2> file` | Send stderr to a file | +| `2>&1` | Send stderr wherever stdout is going | +| `&> file` | Send both to a file (bash) | +| `> file 2>&1` | The portable form of the same | +| `< file` | Read stdin from a file | +| `< /dev/null 2>&1` | Discard everything | +| `<(command)` | Process substitution — a command as a file | +| `tee file` | Write to a file and pass the stream on | -############################################################################## -# COLORS AND BACKGROUNDS -############################################################################## -# note: \e or \x1B also work instead of \033 -# Reset -Color_Off='\033[0m' # Text Reset +```bash +# a heredoc, expanded +cat < config.ini +host=$HOSTNAME +port=8080 +EOF -# Regular Colors -Black='\033[0;30m' # Black -Red='\033[0;31m' # Red -Green='\033[0;32m' # Green -Yellow='\033[0;33m' # Yellow -Blue='\033[0;34m' # Blue -Purple='\033[0;35m' # Purple -Cyan='\033[0;36m' # Cyan -White='\033[0;97m' # White +# a heredoc, literal (quoted delimiter) +cat <<'EOF' > script.sh +echo "$HOME is not expanded here" +EOF -# Additional colors -LGrey='\033[0;37m' # Light Gray -DGrey='\033[0;90m' # Dark Gray -LRed='\033[0;91m' # Light Red -LGreen='\033[0;92m' # Light Green -LYellow='\033[0;93m'# Light Yellow -LBlue='\033[0;94m' # Light Blue -LPurple='\033[0;95m'# Light Purple -LCyan='\033[0;96m' # Light Cyan +# compare the output of two commands without temporary files +diff <(sort a.txt) <(sort b.txt) +``` +## ⚙️ Jobs & Processes -# Bold -BBlack='\033[1;30m' # Black -BRed='\033[1;31m' # Red -BGreen='\033[1;32m' # Green -BYellow='\033[1;33m'# Yellow -BBlue='\033[1;34m' # Blue -BPurple='\033[1;35m'# Purple -BCyan='\033[1;36m' # Cyan -BWhite='\033[1;37m' # White +```bash +# run in the background, and list the jobs +long_task & +jobs -# Underline -UBlack='\033[4;30m' # Black -URed='\033[4;31m' # Red -UGreen='\033[4;32m' # Green -UYellow='\033[4;33m'# Yellow -UBlue='\033[4;34m' # Blue -UPurple='\033[4;35m'# Purple -UCyan='\033[4;36m' # Cyan -UWhite='\033[4;37m' # White +# bring back to the foreground, or resume in the background +fg %1 +bg %1 -# Background -On_Black='\033[40m' # Black -On_Red='\033[41m' # Red -On_Green='\033[42m' # Green -On_Yellow='\033[43m'# Yellow -On_Blue='\033[44m' # Blue -On_Purple='\033[45m'# Purple -On_Cyan='\033[46m' # Cyan -On_White='\033[47m' # White +# Ctrl+Z suspends the foreground job -# Example of usage -echo -e "${Green}This is GREEN text${Color_Off} and normal text" -echo -e "${Red}${On_White}This is Red test on White background${Color_Off}" -# option -e is mandatory, it enable interpretation of backslash escapes -printf "${Red} This is red \n" -``` \ No newline at end of file +# survive logout +nohup ./script.sh > out.log 2>&1 & +disown -h %1 + +# wait for background jobs +wait +wait $! + +# signals +kill 1234 +kill -9 1234 +kill -TERM %1 +pkill -f "node server.js" + +# give a command a deadline +timeout 30s ./slow_task.sh + +# clean up on exit, whatever happens +trap 'rm -f "$tmpfile"' EXIT +trap 'echo interrupted; exit 130' INT TERM +``` + +## 🛡 Safe Scripting + +```bash +#!/usr/bin/env bash +# -e exit on any failing command +# -u treat unset variables as an error +# -o pipefail a pipeline fails if any stage fails +set -euo pipefail + +# make word splitting predictable +IFS=$'\n\t' + +# always quote expansions +cp "$src" "$dest" + +# check the syntax without running anything +bash -n script.sh + +# trace every command as it runs +bash -x script.sh +set -x; risky_command; set +x + +# a more informative trace prefix +export PS4='+ ${BASH_SOURCE}:${LINENO}: ' + +# report where a script died +trap 'echo "failed at line $LINENO with status $?" >&2' ERR + +# and lint it before it reaches anyone else +shellcheck script.sh +``` + +> ⚠️ `set -e` has surprising corners: it does not fire inside `if`, `&&`, `||` or command substitutions used in assignments. It is a seatbelt, not autopilot — still check what matters explicitly. + +## 🎨 Colours + +Escape sequences take the form `\033[