Basics
Updated: October 15, 2024
These are basic commands for using (B)ourne (A)gain (SH)ell. zsh is a shell language, the shell is also referred as the terminal. Zsh is similar and is now becoming the defualt shell for MacOS (Catalina+). zsh is still default for most Linux systems. Watch this beginner video to get comfortable with these basics. Then you can add the other tools onto this knowledge.
One of the benefits about command line tools is the usage is more universal than gui (Graphical User Interface, pronounced goo-eee) conterparts. CLI (Command Line Interface) has more precision and power as well. It is very important to get started and use these in a terminal. In the computer world you can only learn by doing. Use the CLI every time you have a chance. If on windows you will want to install git cli. Powershell sucks and these commands will not work with it. Most of these tools are on a machine by default but as you learn more you will want to download and install more tools but that is for another day.
Table of Contents
- Exit
- Autocomplete
- Keyboard Shortcuts
- Navigation
- Arguments
- Test
- History
- Help
- Directories
- Networking
- Text Editor
- File Descriptors
- Egrep
- Users
- System Info
- Neat Tricks
- Processes
- Watch Logs
- Interupt
- Signals
- Examples
- Runlevels
EXIT & CLEAR
The running joke about vim (the improved version of oldest text editor vi) is that the first exprience a user has in vim is not being able to get out of it (exit). It is ZZ to save and quit and ZQ to quit without saving btw. Shells do generally have a close button on the window. However, if during an ssh session into another machine, using the close button will not close down properly. You do not want to feel like a newbie in vim, so knowing this first command is important.
exit # closes ssh session, closes terminal.
clear # clear screen, just moves text off screen, like a soft reset.
reset # unborks terminal
tput
civis # hides cursor
cnorm # brings cursor back
TAB AUTOCOMPLETE
When typing a word or command or file you can hit tab and it will complete the word or path that you were typing. Sometimes as you are typing you hit tab too soon and there are several words that could be completed but terminal doesn’t know which one you want so it will appear to do nothing. Just hit tab again and it will show you a list of all words starting with what you have typed so far. This will allow you to see the least amount of typing required in order to select the word/path you wanted.
cd Do (tab) # this will do nothing because there is a Download and Documents directory
hit tab again and it will then display:
Downloads Documents # we want to go to Documents so we will add a c and hit tab again
cd Doc (tab) # this will complete the word Documents
KEYBOARD SHORTCUTS
ctrl-d = delet char at cursor
ctrl-l = clear terminal
ctrl-p = recall last command to edit
ctrl-r = search through shell history
ctrl-t = transpose char at cursor
ctrl-c = kill a running command
ctrl-z = suspend current process
ctrl-a = go to beginning of line
ctrl-e = go to end of line
alt-f = move forward by word
alt-b = move backward by word
ctrl-x-e = pop into a buffer that then runs
alt-. = paste arg of last command
ctrl-k = kill(copy) -> cut to end of line
ctrl-u = cut to beginning
ctrl-w = cut by word backwards (space delimited)
alt-bksp = cut by word backwards (stops at special chars)
ctrl-y = yank
ctrl-s = turn off input and output from X!
# Ctrl+Q to turn X back on.
NAVIGATION
~. # ?? not sure about this one: get unstuck if zsh 'hangs' works sometime otherwise ctrl c or q
. # means current directory but can also mean source like:$ ./.zshrc
ls # list of files
cd # change directory
cd - # go back and forth between last directories
pwd # present working directory
pushd # sets location as a home and go to that location.
popd # jumps back to last location of pushd
file # determine file type
locate # find files by name
updatedb # update database for locate on linux
which # locate a command, it's binary or executable
open # open a file or directory gui. ex open .
ARGUMENTS
Arguments are letters behind a dash (-v) or a word following a double dash (–version). There is also a – not followed by a letter or word that is not a flag but rather represents the end of the arguments.
Thus anything that follows – is seen as file names not options.
The following will manipulate or use commands from a previous command. If starting with $ then used more for scripting, if ! then more for running on a command.
$0 # name of current shell or script
$1 # first argument
$@ # list of all arguments
$# # number of arguments
$$ # pid of current shell
$? # exit status of last command
$! # pid of last background process
!! # repeat all arguments of last command
!:n # repeat command arguments from last command
!:n-m # range repeat
!:n-$ # repeat from N to the end
!* # repeat all arguments of last command
!^ # get first argument of last command
!$ # get last argument of last command
^abc^def # run last command, replacing abc with def
TEST
This can really help with making commands or scripts more logical. Test is [ … ] or [[ … ]] where … is an arugment or expression of test.
[ -d $dir ] # test if directory exists
[ -e $file ] # test if file exists
[ -f $file ] # test if file exists and is a regular file
[ -h $file ] # test if file exists and is a symbolic link
[ -k $file ] # test if file exists and sticky bit is set
[ -r $file ] # test if file exists and is readable
[ -s $file ] # test if file exists and is not zero
[ -w $file ] # test if file exists and is writable
[ -x $file ] # test if file exists and is executable
[ -S $file ] # test if file exists and is a socket
file1 -nt file2 # test if file1 is newer than file2
file1 -ot file2 # test if file1 is older than file2
file1 -ef file2 # test if files are the same
SUBSHELLS
Subshells retain the original shell environment. When you exit a subshell any changes dissappear.
Subshells can be nested. Pipes and background processes work with subshells too.
To use a subshell put commands to be executed in parentheses.
( ls ) # subshell
(cd uglydir; uglycmd) # executes uglycmd while in uglydir
(PATH=/usr/confusing:$PATH; uglycmd) # executes uglycmd with PATH set
tar cf - dir | (cd dest; tar xfp -) # duplicates files and folders in dir with permissions faster than cp -r
# target dir must exist before you can use it. [ -d dir -a | dir -ef dest ]
HISTORY
history # display zsh command history
ctrl-R # runs reverse history search, repeat to cycle
history -c # clears history of current browser, needs to be done before next cmd:
rm ~/.zsh_history # permanantly clears terminal history to fresh start.
space # start terminal line with a space to exclude from history
GETTING HELP
whatis # display the on-line manual descriptions
man # reference manual
-f # gives desceription of what a tool does.
-u # update the database of a manpage
1 utility 2 lowlevel 3 c lib function 4 special devices 5 file formats 6 games 7 misc 8 system
apropos # search the manual page names and descriptions
-n # check commands for syntax without executing
-x # echo commands before they are executed.
WORKING WITH FILES | DIRECTORIES
~steve # goes to steves home directory, even while logged in as someone else
mkdir # create a directory/make directories
mkdir -p Website/{static/{cs,js},templates/html} # as an example
rmdir # remove empty directories
touch # change file timestamps/create empty files
cp # copy files and directories
mv # move (rename) files
rm # remove files or directories
chmod # change permissions of a file
-t # remove sticky bit, +t to add
# makes to only owner/root can rename/delete a file
chown # change ownership of a file
-h # change symbolic links but not actual file
-R # recursive (needed for directories) (may also put --max-depth on it)
chgrp # change group of a file
NETWORKING
ping # check for connection on a source
traceroute # traces all the nodes on a route
iftop # displays a table of current bandwidth usage by hosts
TEXT EDITOR
cat # concatenate files and print on the standard output
less # file perusal filter for crt viewing
nano # command line text editor for losers
vim # command line text editor for leet
FILE DESCRIPTORS
#STDIN STDOUT STDERR = 0 1 2
> # replace existing file content or creates new file; redirect STDOUT
>> # appends (adds) input >> @end of a file; Redirect STDOUT
< # connects commands STDIN to contents of existing file
| # called a pipe; connects STDOUT of one command to the STDIN of another
>& # redirect STDOUT and STDERR to the same place
2> # redirect STDERR
2>&1 # redirect STDERR to STDOUT
1>&2 # redirect STDOUT to STDERR
# Short-circuit Evaluation (McCarthy)
&& # first command must succeed for next command to work
|| # next command will execute ONLY if first fails
# good for error handling; || echo "backup failed"
; # place multiple commands on one line
# Using EOF instead of going into editor
cat > /dir/dir/file.ext <<EOF
text you want added or used in piping
with multiple lines and no need to
enter editing, good for not too long of stuff
EOF
EGREP (global regular expression print)
Searches inside of text documents as well. Unlike search find locate etc.
egrep -i # search case insensitive
-v # inverse search (not containing the word)
-l # just show names of file and no sentences
-L # all docs with search term
-c # shows how many times search term appears in a file
-n # same as -c but with line number and sentence word appears in.
-w # search for exact term like Hak but not show Haking Hak5 Hakery etc
-R # search recursively
-rn # rucrusive with line number
USERS
sudo # execute a command as superuser / never use su sudo/ instead:
sudo -s # operate as superuser until you type exit used to be good for linux but really should use:
sudo zsh # back door method for linux since -s & su usually dont work.
-c # gets zsh to execute one command as root.
su # change user ID or become another user
su - Bob # change to Bobs zsh environment and oerate in their directory
users # print the user names of users currently logged in
id # print real and effective user and group IDs
mkpasswd -m sha-512 # generate password
System Info
sysbench --threads=$(nproc) cpu run # test CPU
uname -a # print kernel information
cat /proc/cpuinfo # print cpu information
free -m # print memory information
df -h # print disk information
NEAT TRICKS
sudo !! # run last command as superuser
# create a super fast ram disk
mkdir -p /mnt/ram
mount -t tmpfs tmpfs /mnt/ram -o size=8192M
# fix a really long command that you messed up
fc
# tunnel with ssh ( local port 3337 -> remote host's 127.0.0.1 on port 6379)
ssh -L 3337:127.0.0.1:6379 root@emkc.org -N
-> once connect put in background with bg
# quickly create folders
mkdir -p folder/{sub1,sub2}/{sub1,sub2,sub3}
# intercept stdout and log to file
cat file | tee -a log | cat > /dev/null
# exit terminal but leave all processes running
# useful if your ssh'd somewhere and running a long process you can disown and leave
# so the process will continue to completion even if the connection is severed
disown -a && exit
# !$ # means last argument in the last command
mkdir -p /path/to/new/dir && cd !$
# place command to run in the background
some command &
command | sh -x # runs each file into sh as a execution
WARNING: THIS NEEDS TO BE REDONE DOES NOT FULLY WORK!!
sudo adduser username
sudo passwd username
usermod -aG sudo username
because above is not setting properly
sudo mkdir /home/me
sudo usermod --shell /bin/zsh --home /home/me me
sudo chown -R me:me /home/me
PROCESSES AND LOGGING OUT
some command; read -t 1 -n 10000 discard # keeps keyboard from doing input while cmd runs
nproc # list number of processing units
ps # list process and their ids
ps -ej #
ps aux # list all processes for all users
ps auxf # adds organized tree list
ps U megacron # processes for a specific user
kill 4034 # kills process by id number
killall # kill processes by name
ps aux | egrep nginx
namei -om <path> # shows all privleges along the path
Use less +F instead of tail -f
less +F /var/logs/system
ctrl+c = detatch so you can scroll up
shift+f = reattatch
SOME COMMANDS NEED CTRL+C TO STOP
These commands will continue to run until sent a signal to stop. See SIGNALS the full list. Most are used in programming and not in terminal. Mostly just ctrl + c and ctrl + z.
watch # runs a command every 2s
free # shows how much memmory is in a system
top # displays system resource usage
htop # displays system resources but in gui (requires install)
SIGNALS
HUP (1): Hangup
INT (2): Interrupt
QUIT (3): Quit (generates a core dump used for debugging, 15 does not)
ILL (4): Illegal instruction
ABRT (6): Abort
FPE (8): Floating point exception
KILL (9): Kill (cannot be caught or ignored)
SEGV (11): Segmentation fault
PIPE (13): Broken pipe
ALRM (14): Alarm clock
TERM (15): Termination request (gracefully)
USR1 (10): User-defined signal 1
USR2 (12): User-defined signal 2
CHLD (17): Child process terminated or stopped
CONT (18): Continue executing
STOP (19): Stop executing (cannot be caught or ignored)
TSTP (20): Stop from keyboard
TTIN (21): Background process attempting read from terminal
TTOU (22): Background process attempting write to terminal
EXAMPLES
Here is an example of common use cases on the command line.
ls -al / > lsout.txt # creates lsout.txt from the output listing our home directory
history | less # puts list of used commands into a page viewer
cat >> file3 # add notations to end of file3
watch -n 60 hddtemp /dev/sd[c,d,e] # monitor drive temps
RUNLEVELS
- Run level 0 is matched by poweroff.target (and runlevel0.target is a symbolic link to poweroff.target).
- Run level 1 is matched by rescue.target (and runlevel1.target is a symbolic link to rescue.target).
- Run level 3 is emulated by multi-user.target (and runlevel3.target is a symbolic link to multi-user.target).
- Run level 5 is emulated by graphical.target (and runlevel5.target is a symbolic link to graphical.target).
- Run level 6 is emulated by reboot.target (and runlevel6.target is a symbolic link to reboot.target).
- Emergency is matched by emergency.target.
We can use systemctl isolate to change the runlevel. Runlevel is a initd reference, whereas reboot.target is a systemd reference.
In either case, these commands will change the runlevel wether initd or systemd because of the symbolic links.
sudo systemctl isolate runlevel0.target
sudo systemctl isolate runlevel1.target
sudo systemctl isolate runlevel3.target
sudo systemctl isolate runlevel5.target
sudo systemctl isolate runlevel6.target
To change using systemctl
# Get current runlevel
sudo systemctl get-default
# change to runlevel 3
sudo systemctl set-default runlevel3.target