Shell Tools and Scripting

Shell Scripting

foo=bar
echo "$foo"
# prints bar
echo '$foo'
# prints $foo
mcd () {
  mkdir -p "$1"
  cd "$1"
}

Special Characters

More info: Chapter 3. Special Characters

shell globbing (通配符匹配)

convert image.{png,jpg}
# Will expand to
convert image.png image.jpg

cp /path/to/project/{foo,bar,baz}.sh /newpath
# Will expand to
cp /path/to/project/foo.sh /path/to/project/bar.sh /path/to/project/baz.sh /newpath

# Globbing techniques can also be combined
mv *{.py,.sh} folder
# Will move all *.py and *.sh files


mkdir foo bar
# This creates files foo/a, foo/b, ... foo/h, bar/a, bar/b, ... bar/h
touch {foo,bar}/{a..h}
touch foo/x bar/y
# Show differences between files in foo and bar
diff <(ls foo) <(ls bar)
# Outputs
# < x
# ---
# > y
            # Find all python files where I used the requests library
            rg -t py 'import requests'
            # 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

array
an associative array

BashFAQ - Greg's Wiki