Bash - BKJackson/BKJackson_Wiki GitHub Wiki

Bash Tutorials (#!/bin/bash)

Learn Bash in Y Minutes
How to Create and Use Bash Scripts
Find command exclude ignore examples
How to call a shell script from another shell script
Linux Bash exit and Exit Codes

Bash Conditionals

To compare strings use: =, !=, <, >
To compare integers: -eq, -ne, -lt, -gt, -le, -ge
To compare expressions: !, -a, -o (not, and, or)
Booleans: 0, 1, (>0 means error occurred)
Compound expressions: &&, !!

Grouping Bash commands

( command; command;...) : creates a subshell environment. Parentheses are operators, not required to be separated from the list by whitespace.
{ command; command; } : executes commands in current shell. Braces are reserved words, must be separated from the list by whitespace.

Combining commands

# Substitute commands in other commands with $()
# Print list of files in current directory
echo "There are $(ls | wc -l) items here."

# Print list of files with .txt extension
ls -l | grep "\.txt" 

Combining parameters

# Find files with .ipynb extension and not .* files (such as the .ipynb_checkpoints)    
find . -type f \( -iname "*.ipynb" ! -iname ".*" \)

Expansion parameters

Many types of expansion parameters exist. See "info bash."

Bash Flow Control: if/then/else/fi

if [ $Name != $USER ] && [ "$Age" -eq 15 ]
then
    echo "Your name isn't your username"
else
    echo "Your name is your username"
fi

Bash Flow Control: case/in/esac

Similar to switch in C++ and Java

case "$Variable" in
    #List patterns for the conditions you want to meet
    0) echo "There is a zero.";;
    1) echo "There is a one.";;
    *) echo "It is not null.";;  # Default case
esac

Bash Loops: for/do/done

Note the many evaluation expressions to set up a loop Bash for loops iterate for each of the arguments given in the evaluation expression.

# Traditional for loop
for ((a=1; a <= 3; a++))
do
    echo $a
done

# Loop over files 
# Run the command 'cat' on file1 and file2
for Variable in file1 file2
do
    cat "$Variable"
done

# The contents of $Variable is printed three times.
for Variable in {1..3}
do
    echo "$Variable"
done

# This takes the output from a command
# This will cat the output from ls
for Output in $(ls)
do
    cat "$Output"
done

Bash while/do/done loop

while [ true ]
do
    echo "The condition is true..."
    break
done

Bash until/do/done loop

Like a while [not true] loop

until [ true ]
do 
    echo "It is not true yet..."
    break
done

Bash select/do/done

Similar to a for loop that executes for each item in a list.

select fname in *;
do 
    echo You picked $fname 
    break;
done

Bash Functions

With or without the keyword "function."
Note that an integer is returned like in C++ and no semicolons are used to terminate statements.
The functions below are called with simply "foo" or "bar."

# With the function keyword
function foo ()
{
    echo "Arguments work just like script arguments: $@"
    echo "And: $1 $2..."
    echo "This is a function"
    return 0    
}

# Without the function keyword
bar ()
{
    echo "Another way to declare functions"
    return 0
}

Other useful commands

tail -n 5 file.txt  # Print the last 5 lines of file.txt
head -n 5 file.txt  # Print the first 5 lines of file.txt
sort file.txt       # Print sorted contents of file.txt (empty lines are printed first)
uniq file.txt       # Print unique lines in file.txt
uniq -d file.txt    # Print repeated lines (-d option) in file.txt (excludes empty lines)
cut -d ',' -f 1 file.txt    # Print first column before ',' character
sed -i '.bak' 's/std/OMG/g' file.txt   # Replace std w/OMG & save file.txt backup as file.txt.bak
grep "^foo.*bar$" file.txt   # Print all lines of file.txt which begin w/foo and end w/bar
grep -c "^foo.*bar$" file.txt   # Print a count of matching lines instead of the text
grep -F "foobar" file.txt    # Print lines containing exact string
fgrep "foobar" file.txt      # Print lines containing exact string (same as grep -F)

Bash redirections

'/dev/tcp/HOST/PORT' If HOST is a valid hostname or Internet address, and PORT is an integer port number or service name, Bash attempts to open a TCP connection to the corresponding socket.

'/dev/udp/HOST/PORT' If HOST is a valid hostname or Internet address, and PORT is an integer port number or service name, Bash attempts to open a UDP connection to the corresponding socket.

Bash Help for builtin shell commands

Note: Builtin Bash shell commands are not covered in man pages.

help              # Output includes list of Bash commands
help help         # Prints help short synopsis
help for          # Print help for keyword "for"
help source       # Print help for command "source"
help .            # Print help for operator "." 

Other documentation: Man, Apropos, and Info

Apropros - Searches the whatis database for strings

apropos <string>       # Search whatis database for <string>
apropos bash           # Returns bash(1) and bashbug(1)
apropos csh            # Returns tcsh (C shell)
apropos info | grep '^info.*('   # Return file list w/title "info" & internal "info"  

Man - Formats and displays on-line manual pages

man bash               # Returns man page for bash, the definitive bash reference   
man man                # Returns man page for man  
man grep               # Returns man page for grep 

Info - Reads GNU Project online manuals in the Info format.

info info             # Returns info documentation and help on how to use Info  
info bash             # Returns an intro to Bash shell (Very long and detailed)  
info bash 'Bash Features'   # Returns a subsection of "info bash"
info --apropos bash   # Returns list of all manuals containing the string "bash" 

Other popular shells

sh     # Bourne shell  (Note: bash = Bourne-Again SHell)
ksh    # Korn shell  
csh    # C shell  
tcsh   # Successor to the C shell  

Misc Bash process details to remember

PID - Process group ID. A unique identifier that represents a 'process group' during its lifetime.
Single quotes suppress all interpretation of a sequence of characters, while double quotes suppress most but not all interpretation ($, ', , *, @, and ! when history expansion is enabled).
Pipeline format: ['time' ['-p']] ['!'] COMMAND1 ['|' COMMAND2 ...], where 'time' prints timing statistics.
Control operator '&' following a command executes the command asynchronously in a subshell (i.e., in the background).
Commands separated by ';' execute sequentially.
AND execution CMD1 && CMD2: CMD2 executes if and only if CMD1 returns exit status 0.
OR execution CMD1 || CMD2: CMD2 executes if and only if CMD1 returns a non-zero exit status.

⚠️ **GitHub.com Fallback** ⚠️