Linux System Information
Linux System Information
Linux System Information
Command Description
uptime Show how long the system is running and load information.
w Display what users are online and what they are doing.
su Superuser; use this before a command that requires root access e.g. su shutdown
man COMMAND Shows the manual for a given COMMAND. To exit the manual, press “q”.
Input/Output Redirection
These are helpful for logging program output and error messages.
Command Description
echo -e TEXT Also interprets escape characters in TEXT, e.g. \n → new line, \b → backslash, \t → tab.
| is the pipe character; feeds the output of the command cmd1 and sends it to the command cmd2, e
cmd1 | cmd2
grep python3.
cmd > file Output of cmd is redirected to file. Overwrites pre-existing content of file.
cmd >
Suppress the output of cmd.
/dev/null
Input of cmd is read from the standard input with the delimiter character delim to tell the system wh
terminate the input. Example for counting the number of lines of ad-hoc input:
wc -l << EOF
> I like
> apples
cmd << delim
> and
> oranges.
> EOF
4
Hence there are only 4 lines in the standard input delimited by EOF.
File Management
In the following commands: X may refer to a single file, a string containing a wildcard symbol referring to
a set of multiple files e.g. file*.txt, or the stream output of a piped command (in which case the syntax
would be X | command instead of command X); Y is a single directory; A and B are path strings of
files/directories.
Command Description
* Wildcard symbol for variable length, e.g. *.txt refers to all files with the TXT extension.
? Wildcard symbol referring to a single character, e.g. Doc?.docx can refer to Doc1.docx, DocA.docx, et
List the names of files and subfolders in the current directory. Options include -l, -a, -t which may be
ls
e.g. -alt.
Also show details of each item displayed, such as user permissions and the time/date when the item
ls -l
modified.
ls -t Sort the files/folders according to the last modified time/date, starting with the most recently modifi
Compare two files A and B for sameness. No output if A and B are identical, outputs character and lin
cmp A B
otherwise.
diff A B Compare two files A and B for differences. Outputs the difference.
Move a file from path A to path B. Also used for renaming files.
Examples:
Moving between directories folder1 and folder2:
mv A B mv ./folder1/file.txt ./folder2
The file name will remain unchanged and its new path will be ./folder2/file.txt.
Renaming a file: mv new_doc.txt expenses.txt
The new file name is expenses.txt.
Copy a file from path A to path B. Usage similar to mv both in moving to a new directory and simulta
renaming the file in its new location.
cp A B
Example: cp ./f1/file.txt ./f2/expenses.txt simultaneously copies the file file.txt to the new location w
name expenses.txt.
Recursively copy a directory Y and its contents to Z. If Z exists, copy source Y into it; otherwise,
cp -r Y Z
create Z and Y becomes its subdirectory with Y’s contents
touch X Create an empty file X or update the access and modification times of X.
Display the first lines of X. If more than a single file is specified, each file is preceded by a header con
head X
the string "==> X <=='' where "X'' is the name of the file.
ls *.c | head -
Display the first 5 items of a list of *.c files in the current directory.
n5
Display the last part of X. If more than a single file is specified, each file is preceded by a header cons
tail X
the string "==> X <==" where "X" is the name of the file.
tail -n +1 X Display entire contents of the file(s) X specified, with header of respective file names
less Read a file with forward and backward navigation. Often used with pipe e.g. cat file.txt | less
MEMBERSHIP →
00
days
03
hrs
13
mins
49
secs
Command Description
Search for a text pattern patt in X. Commonly used with pipe e.g. ps aux | grep python3 filter
grep patt X
processes containing python3 from all running processes of all users.
grep -l patt X Only the names of files containing patt are written to standard output.
find /path/to/src -
Find all files in /path/to/src matching the pattern "*.sh" in the file name.
name "*.sh"
find .. -size +2M Find all files in the parent directory larger than 2MB.
Archives
Command Description
tar -tf archive.tar List contents of the TAR archive named archive.tar.
tar -czf archive.tar.gz Y Create a gzip-compressed TAR archive named archive.tar.gz containing Y.
tar -xzf archive.tar.gz Extract the gzip-compressed TAR archive named archive.tar.gz.
tar -cjf archive.tar.bz2 Y Create a bzip2-compressed TAR archive named archive.tar.bz2 containing Y.
tar -xjf archive.tar.bz2 Extract the bzip2-compressed TAR archive named archive.tar.bz2.
File Transfer
Command Description
scp [user1@]host1:[path1] Login to hostN as userN via secure copy protocol for N=1,2. path1 and path2
[user2@]host2:[path2] local or remote. If user1 and user2 are not specified, your local username wil
scp -r [user1@]host1:[path1]
Recursively copy all files and directories from path1 to path2.
[user2@]host2:[path2]
Login to access as user via secure file transfer protocol. If user is not specified
sftp [user@]access
username will be used.
File Permissions
Not all files are equally accessible. To prevent unwanted tampering, some files on your device may be
read-only. For more information about file permissions on Unix, refer to our Linux File Permissions
Cheat Sheet, as the same content applies to Unix.
Command Description
chmod permission Change permissions of a file or directory. Permissions may be of the form [u/g/o/a][+/-/=][r/w/x
file examples below) or a three-digit octal number.
Command Description
Usage examples:
chmod u-w testfile → forbid the current user from writing or changing the file
chmod u+wx,g-x,o=rx testfile → simultaneously add write & execute permissions to user, remove
execute permission from group, and set the permissions of other users to only read and write.
Numeric Representation
0 No permissions -rwx
Examples
chmod 177 testfile → restrict current user (u) to execute-only, while the group (g) and other
users (o) have read, write and execute permissions
chmod 365 testfile → user (u) gets to write and execute only; group (g), read and write only;
others (o), read and execute only.
Process Management
The following is redolent of functions in Windows’ Task Manager, but on the command line.
Command Description
& Add this character to the end of a command/process to run it in the background.
Show process status. Often used with grep e.g. ps aux | grep python3 displays information o
processes involving python3.
ps Meaning of aux:
a = show processes for all users
u = show user or owner column in output
x = show processes not attached to a terminal
ps -e
Either of these two commands prints all running processes in the system.
ps -A
ps -U root -u root Display all processes running under the account root.
ps -eo
Display only the columns PID, USER and COMMAND in ps output.
pid,user,command
kill PID Kill a process specified by its process ID PID, which you may obtain using the ps command.
List all open files on the system. (This command helps you pinpoint what files and processes
lsof
preventing you from successfully ejecting an external drive.)
Networking
These commands regulate how your Unix machine communicates with other computers, such as the
local area network (LAN) router or external websites.
Command Description
Print open sockets of network connections, routing tables, interface statistics, masquerade connectio
multicast memberships.
netstat
This command is often piped with the less command:
e.g. netstat -a | less
ping host Send ICMP echo request to host, which may be a symbolic name, domain name or IP address.
whois
Display whois information for domain.
domain
Built into Unix systems, vi (or vim) is a command-line visual editor. For simple text file manipulation, the
following commands will suffice.
Command Description
vi -R X
Open an existing file X in read-only mode.
view X
Command Description
:w Save changes.
Enter insert mode and amend the opened file. To return to command mode and use the other comman
i
table, press the ESC key.
o Enter insert mode and add a new line underneath the cursor.
r Replace the character under the cursor location with the key the user presses next.
:%s/foo/bar Replace every instance of “foo” with “bar” in the open file.
Command Description
# Designates all text after # on the same line to be comments (not executed).
#!/bin/sh Alert the system that a shell script is being executed. Used as the first line of the shell script.
Vi Cheat Sheet
Variables
Valid Shell variable names contain alphanumeric [A-Z, a-z, 0-9] characters and/or underscore (_). The
variable must begin an alphabetical character and is usually uppercase.
Command Description
Define a variable VAR_NAME and give it a VALUE. The value may be a number or string enclos
double quotation marks ("). Examples:
VAR_NAME=VALUE
PRICE=100
PERSON="John Smith"
Reserved Variables
By using any of the following in your shell scripts, you call values from special variables in Unix.
Variable Description
$1, $2, $3, …, ${10}, References to the arguments supplied to the script: $1 is the first argument, $2 is the sec
${11}, … argument, and so on.
$* Refer to arguments separated by spaces. Here, "a b c" d e are considered 5 separate argu
Refer to arguments grouped by the double quotes enclosing them. Here, "a b c" d e are c
"$@"
3 arguments.
The exit status of the last command executed: 0 for success and 1 or other numbers for v
$?
errors.
Arrays
Accessing array values (zero-indexed, i.e. first element is at [0] not [1]):
MEMBERSHIP →
00
days
03
hrs
13
mins
49
secs
Basic Operators
These are used in the expressions in decision making and loop control.
For arithmetic and relational operators, the arguments are applied to both sides of each operator,
separated by spaces, e.g. 2 + 2 (not 2+2).
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
= Assignment
== Equality
!= Inequality
-eq Equal to
!= Returns true if the two operands on both sides of != are not equal.
-f $FILE Returns true if FILE is an ordinary file as opposed to a directory or special file.
Types Syntax
if [ expression ]
then
if…fi
Statement(s) to be executed if expression is true
fi
if [ expression ]
then
Statement(s) to be executed if expression is true
if…else…fi
else
Statement(s) to be executed if expression is false
fi
if [ expression1 ]
then
Statement(s) to be executed if expression1 is true
elif [ expression2 ]
then
Statement(s) to be executed if expression2 is true
if…elif…else…fi
elif [ expression3 ]
then
Statement(s) to be executed if expression3 is true
else
Statement(s) to be executed if none of the given expressions is true
fi
esac
Loop Control
Note: word1 word2 … wordN may be a list of numbers (e.g. 1 2 3 4 5) or a set of paths (e.g. /home/folder
while command
do
Statement(s) to be executed if command is true
while
done
until command
do
until
Statement(s) to be executed until command is true
done
Available in ksh and bash but not sh. Behaves like a for-loop with the numbers replaced by the words.
continue Exit the current iteration of the loop and proceed with the next iteration.
Flow control Syntax
Ctrl+L Key combination to remove the previous command and its output (macOS: command+L)