Shell Tools and Scripting

PrettyMeng, code

Shell Scripting

Why shell scripting?

Assign variable in bash

Define string with '' or "":

foo=bar
echo "$foo"
# prints bar
echo '$foo'
# prints $foo

Define functions

mcd () {
mkdir -p "$1"
cd "$1"
}
source mcd.sh
mcd test

This will mkdir a directory named test and cd into it.

Special Variables

Logical operators with short-circuiting features

false || echo "Oops, fail"
# Oops, fail
true || echo "Will not be printed"
#
true && echo "Things went well"
# Things went well
false && echo "Will not be printed"
#
true ; echo "This will always run"
# This will always run
false ; echo "This will always run"
# This will always run

Get the output of a command as a variable/file

A comprehensive example

#!/bin/bash
echo "Starting program at $(date)" # Date will be substituted
echo "Running program $0 with $# arguments with pid $$"
for file in "$@"; do
grep foobar "$file" > /dev/null 2> /dev/null
# When pattern is not found, grep has exit status 1
# We redirect STDOUT and STDERR to a null register since we do not care about them
if [[ $? -ne 0 ]]; then
echo "File $file does not have any foobar, adding one"
echo "# foobar" >> "$file"
fi
done

Shell globbing

Shellcheck

Shebang

Difference between functions and scripts

Shell Tools

Documentation about how to use commands

Finding files matching some criteria

# Find all directories named src
find . -name src -type d
# Find all python files that have a folder named test in their path
find . -path '*/test/*.py' -type f
# Find all files modified in the last day
find . -mtime -1
# Find all zip files with size in range 500k to 10M
find . -size +500k -size -10M -name '*.tar.gz'

Besides listing files, find can also perform actions over files that match the query.

# Delete all files with .tmp extension
find . -name '*.tmp' -exec rm {} \;
# Find all PNG files and convert them to JPG
find . -name '*.png' -exec convert {} {}.jpg \;

Finding code

# Find all python files where I used the requests library in a specified folder
rg -t py 'import requests' ~/scratch
# Find all files (including hidden files) without a shebang line
rg -u --files-without-match "^#!"
# Find all matches of foo and print the following 5 lines
rg foo -A 5
# Print statistics of matches (# of matched lines and files )
rg --stats PATTERN

Finding commands

Directory navigation

Exercise

ls -a -h -t -color
CC BY-NC 4.0 © PrettyMeng.RSS