Sunday, August 25, 2019

Bash Programming 筆記


Bash shebang:
#!/usr/bin/env bash

Another common bash shebang (force bash):


Common Ifs

Check File Exist:
if [ -e <file_name> ]; then

Check Variable Valid:
if [ -v Variable ]; then

Check variable not zero length:
if [ -z "$variable" ]; then


Syntax Checking

Debugging (Print everything):
bash -x <your script>
set -x (activate debug) / set +x (deactivate debug)

Syntax Checking:

bash -n <filename>


Useful Tools

Compare two files, show only lines unique to file 1:
comm -2 -3 <file 1> <file 2>

Show only first few bytes of a file:
head -c6     #only first 6 bytes

Do some simple math:
expr 9 / 3

Easy awk (here selecting first item with delimiter ' '):
cut -d " " -f 1

Capitalizing characters (translate characters)
tr "a-z" "A-Z"

Use xargs to remove unnecessary heading and trailing space:
echo "   google  " | xargs     # result = "google"


Parameters Expansion: