Merikanto

一簫一劍平生意,負盡狂名十五年

LPIC - 109 Scripting

More reference - Scripting (Tag)


Shell Environment

1 - Shell Config

Global & Local vars

  • Global - Available from current shell & any child processes spawned from the shell
    • printenv - Show all global env vars 📌
    • export - make var available to all programs launched from the shell
  • Local - Only available in the shell that creates it
    • set - Show all env vars for a specific process
    • env - set var for just one program
    • Recommend using lowercase letters (distinguish from system env vars)
1
2
3
4
5
# var is available to all
export FCEDIT=/usr/bin/vim

# var is available for one program
env FCEDIT=/usr/bin/vim mail

Common env vars

Note: For multiple X sessions, DISPLAY always starts with 0:0 for the first session, then 1:0

Variable Explanation
SHELL Path to current shell
HOSTNAME Current hostname
PS1 Default bash prompt
TERM Current terminal type (e.g. xterm)
DISPLAY Identify X display. Usually 0:0

3 Ways to start Bash shell

  • At login time - As default login shell
  • Interactive shell (launched via Terminal GUI)
  • Non-interactive shell - To run a script

Shell config files

  • Global
    • Login - /etc/profile (main default startup file)
    • Interactive - /etc/bashrc
  • User
    • Login - ~/.bash_profile
    • Interactive - ~/.bashrc
  • ~/.inputrc - Customize keyboard config
    • X uses its own keyboard config. So this doesn’t affect programs running in X


Shell Scripting

1 - General

Notes

  • Piping - Redirect output to another command

  • Run script directly from command prompt - New subshell

  • Make local shell env vars availbale in the script 📌

    1
    exec ./xx.sh

Shebang / hashbang

  • #! - Tells Linux it’s a script
  • /bin/bash - Path to interpreter to run the shellscript (e.g. Bash)

Source a script

  • Run in the current shell. Script has access to env vars defined in the calling shell. 📌
  • source ~/.bashrc
  • . ~/.bashrc

Shell Variables

  • $0 - Script name

  • $$ - PID of current shell

  • $? - Exit status of last command (e.g. 0)

    1
    2
    # change exit status (from 0 to 120)
    exit 120

Command-line Arguments

1
2
3
4
5
# example - test.sh
echo $1 checked in $2 days ago

# run the script
./test.sh Merikanto 10

Command Substitution

  • Assign the command’s output to a user var in the script
  • Can also capture function output using $() 📌
1
2
3
4
5
6
7
8
# use ``
v1=`date`

# or $()
v2=$(who)

echo $v1
echo $v2

File Descriptor

  • Non-negative number
  • 0 - STDIN (keyboard)
  • 1 - STDOUT
  • 2 - STDERR

Read input

Silent reading - Text is displayed, but sets text color same as terminal background color 📌

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# read & use input
read name
useradd -aG $name

# specify a prompt
read -p "Your name:" first last
echo -n "Hello $last, $first" # -n: suppress newline char

# read password / silent reading
read -s -p "Password: " pass

# use timer
read -t 5 -p "Your name:" name # timeout is 5s

# count input char
read -n1 -p "Enter [Y/N]" answer # 1 char, Y or N

Running multiple commands

1
2
# use ;
date; who

List all active aliases

1
alias -p

2 - Synatx

Math

  • Floating point arthmetic is controlled by a built-in var - scale (set to desired number of decimals) 📌
  • zsh - Supports advanced math functions & features
1
2
3
4
5
6
7
8
9
# $[] - int only
result=$[ 25 * 5 ]

# floating point calc
scale=3
bc

# substitute as var
v1=$(echo "scale=3; 2.0/3" | bc)

Condition Tests - Numeric

Test - If [ … ] Description
n1 -eq n2 n1 == n2
n1 -ne n2 n1 != n2
n1 -ge n2 n1 >= n2
n1 -gt n2 n1 > n2
n1 -le n2 n1 <= n2
n1 -lt n2 n1 < n2

Condition Tests - File

Test - If [ … ] Description
-e [file] If file exists
-f [file] If file exists & is a file
-d [file] If file exists & is a directory
-s [file] If file exists & not empty
-r [file] If file exists & readable
-w [file] If file exists & writeable
-x [file] If file exists & executable

Logics - Combine tests with boolean symbols

  • && - And
  • || - Or

If

1
2
3
4
5
6
if [ ... ]
then
...
else
...
fi

Case

1
2
3
4
5
6
7
8
9
10
11
# input is 1 char, Y or N
read -n1 -p "Enter [Y/N]" answer

case $answer in
Y | y) echo "\nOK, continue...";;

N | n) echo "\nBye"
exit;;

*) echo "\nWrong Input"
exit;;

For

seq - Similar to range(), but is [a, b] (闭区间)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# execute 4 times, default interval = 1
for x in `seq 2 5`

# example
for file in $(ls | sort) ; do
if [ -d $file ]
then
echo "$file is a directory"
fi

if [ -f $file ]
then
echo "$file is a file"
fi
done

While

1
2
3
4
while [ ... ]
do
...
done

Function

Use return to specify single int value to define exit status

1
2
3
4
5
6
7
8
9
# Format 1
function hello {
...
}

# Format 2
hello() {
...
}

Example - Putting it altogether

Accepts source & target filename. Aborts when target file exits

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash

doit() {
cp $1 $1
}

function check {
if [ -s $2 ]
then
echo "Target exits. Exiting..."
exit
fi
}

check $1 $2
doit $1 $2

3 - SQL Queries

All Syntax is used in MySQL

Update

1
2
UPDATE objects SET size=5 
WHERE name="lizard";

Exact Matches

1
2
SELECT * FROM objects 
WHERE color="green";

Multiple Tests

Return an ordered list

1
2
3
4
SELECT * FROM objects 
WHERE type="soft"
AND value>7.50
ORDER BY value;

Deletion

1
2
3
4
5
# delete all data from a table (keeps the table)
DELETE * from objects;

# delete table
DROP TABLE objects;

Other Syntax

  • JOIN - combine data from multiple tables
  • GROUP BY - Used with math operators, e.g. SUM()
1
2
3
4
SELECT objects.name, objects.value, SUM(value)
FROM objects, locations
WHERE locations.name=objects.name
GROUP BY value;