Topic 715: Basic Unix Skills and Shell Scripting
This topic covers using the shell, managing files, processes, regular expressions, editing with vi, and writing simple shell scripts. Detailed explanations and examples are provided below.
715.1: Use the Shell and Work on the Command Line
Environment Variables:
-
Bourne shell example:
export PATH=/usr/local/bin:$PATH
Prepends
/usr/local/bin
to the current PATH. -
csh/tcsh example:
setenv PATH /usr/local/bin:$PATH
Sets the PATH variable in C shell environments.
Redirection and Pipes:
-
Output redirection:
ls > files.txt
Saves the output of
ls
intofiles.txt
. -
Input redirection:
cat < files.txt
Reads the contents of
files.txt
. -
Pipe example:
ls | grep conf
Passes the output of
ls
togrep
to filter for lines containing "conf".
Manpages and Documentation:
-
View a manpage:
man ls
-
Search for commands:
apropos network
History and Aliases (csh/tcsh):
-
View history:
history
-
Create an alias:
alias ll 'ls -l'
715.2: Perform Basic File Management
Copying Files and Directories:
-
Copy a file:
cp file1 file2
-
Copy a directory recursively:
cp -r dir1 dir2
Moving Files:
-
Rename or move:
mv oldname newname
Removing Files and Directories:
-
Remove a file:
rm file.txt
-
Remove a directory recursively:
rm -r directory
Identifying File Types:
-
Determine file type:
file something.bin
Archiving/Backup:
-
Create a tar archive:
tar cvf myarchive.tar mydir
-
Extract a tar archive:
tar xvf myarchive.tar
715.3: Create, Monitor and Kill Processes
Monitoring Processes:
-
Interactive process viewer:
top
-
List processes:
ps aux | grep ssh
Killing Processes:
-
Graceful termination:
kill <pid>
-
Force termination (SIGKILL):
kill -9 <pid>
Changing Process Priority:
-
Renice a process:
renice +5 <pid>
Background and Foreground Jobs:
-
Run in background:
some_command &
-
List background jobs:
jobs
-
Bring job to foreground:
fg %1
715.4: Use Simple Regular Expressions
Using grep:
-
Basic search:
grep "error" /var/log/messages
-
Case-insensitive search:
grep -i "warning" /var/log/messages
-
Exclude a pattern:
grep -v "notice" /var/log/messages
Using egrep:
-
Extended regex search:
egrep "ab{2,3}c" file.txt
715.5: Perform Basic File Editing Operations (vi)
Basic vi commands:
-
Save the file:
:w
-
Quit vi:
:q
-
Quit without saving:
:q!
-
Force save and quit:
:wq!
Line operations in vi:
-
Delete a line:
dd
-
Yank (copy) a line:
yy
-
Paste a line:
p
Searching in vi:
-
Search for a pattern:
/pattern
-
Repeat the search:
n
715.6: Customize or Write Simple Scripts
Example script (Bourne shell):
#!/bin/sh
# A simple backup script
BACKUPDIR="/backup"
SRCDIR="/home/user"
tar cvf $BACKUPDIR/home.tar $SRCDIR
echo "Backup completed!"
To make a script executable, use:
chmod +x backup.sh
./backup.sh
In shell scripting, positional parameters allow access to arguments passed to the script:
#!/bin/sh
echo "Script name: $0"
echo "First argument: $1"