Shell Basics
Documentation
man
- By Default the system documentation/manuals are documented in the man pages
# Usage:
man <COMMAND>
help
- Lists all the internal commands of shell
# Usage:
help
Bash structure
~/.bashrc
- configure the shell, define command aliases and set command shell options~/.bash_profile
- initialization commands that set environment variables, a shell’s prompt~/.bash_logout
- cleanup operations and other commands that you want the shell to execute whenever a user logs out of a shell~/.bash_aliases
- if storing many aliases commands
Shell Script
set -x # Enable RAW i/o
set -v # Enable RAW i/o
set -e # abort on error(non-zero exit code)
set -u # detect unset variables
variable=${VARIABLE_NAME:-default} # default value if variable empty
$(( (1+1)/5 )) # Arthematic operation
${1..10} # Sequence
${var%suffix} # trim a suffix named 'suffix'
${var#prefix} # trim a prefix named 'prefix'
${foo,bar} # expand into multiple values
diff /etc/hosts < (ssh somehost cat /etc/hosts) # parenthesis to execute a sub-process
{..} # Include code in between this block, as a good practice
cat <<EOF
touch somefile
echo foo > somefile
EOF
# Bash Script strict mode
#!/bin/bash
set -euo pipefile
IFS=$'\n\t'
Redirection
File Descriptors
- every file has an associated number called FD. Default ones are
0
- STDIN1
- STDOUT2
- STDERR
Types of redirection
>
- STDOUT redirection to file,overwrites at destination
# Usage:
ls -lrt > test.out
>>
- STDOUT redirection to file,appends at destination
# Usage:
ls -lrt >> test.out
<
- STDIN redirection from a file
# Usage:
wc < input_file.out
File Descriptors
based redirection
# Usage:
# Redirect the STDERR to STDOUT
ls -lrt 2>&1
|
- redirects STDOUT of one command into the STDIN of a second command
# Usage:
# Redirect the STDOUT to STDIN
ls -lrt | wc
Navigation
Ctrl + a
- Go to beginningCtrl + e
- Go to endAlt + b
- Go back one wordAlt + f
- Go forward one wordCtrl + w
- Delete a word backwardAlt + d
- Delete next wordCtrl + u
- Delete to beginning of line OR delete lineCtrl + k
- Delete to endCtrl + r
- Search backwards(recursive)Ctrl + s
- Search forwardsCtrl + l
- clears the screenAlt + t
- transpose the last 2 words/characters
Job Management
&
- background process.ctrl+z
- pauses the process temporarily, and places it inSUSPENDED
mode.fg
- used to bring a background / paused process back to the foreground and continue its execution.bg
- resume anySUSPENDED
jobs and run them in backgroundjobs
- check the job status of all the jobskill
- used for killing a process- Status: SUSPENDED, CONTINUED, RUNNING, STOPPED
# Usage:
sleep 100 & # Run the command as a backgroud process
jobs # view all the jobs
jobs -l # view all the jobs along with their job ID & process PID
fg %<JOB_ID> # Resume the job in fore-ground which has the JOB_ID
bg %<JOB_ID> # Resume the job in the back-ground which has the JOB_ID
ctrl+z # Pauses executing of the current running job
ctrl+c # terminates the current executing process