Basic Linux Commands
ls (list — shows files and directories in the current directory; ls -l for a detailed listing, same as ll)
[root@linux ~]# ls [-aAdfFhilRS] directory
[root@linux ~]# ls [--color={none,auto,always}] directory
[root@linux ~]# ls [--full-time] directory
Options:
-
-a: list everything, including hidden files (those starting with.) -
-A: list everything including hidden files, but excluding the.and..directories -
-d: list only the directory itself, not its contents -
-f: list results directly without sorting (lssorts by filename by default) -
-F: append an indicator based on the file type, for example:*for executables;/for directories;=for sockets;|for FIFOs -
-h: show file sizes in human-readable form (GB, KB, etc.) -
-i: list inode numbers instead of file attributes -
-l: long format, including file attributes and so on -
-n: list UID and GID rather than user and group names (UIDs and GIDs come up in account management) -
-r: reverse the sort order — for instance, filenames descending instead of ascending -
-R: list subdirectory contents too -
-S: sort by file size -
-t: sort by time -
--color=never: don’t colorize output based on file type -
--color=always: always show colors -
--color=auto: let the system decide whether to colorize -
--full-time: output in full time format (year, month, day, hour, minute) -
--time={atime,ctime}: output the access time or the permission/attribute change time (ctime), rather than the content modification time
cat — display file contents starting from the first line
[root@linux ~]# cat [-AEnTv]
Options:
-
-A: equivalent to-vETcombined; shows special characters -
-E: show the line-ending character as$ -
-n: print line numbers -
-T: show[tab]as^I -
-v: show otherwise invisible special characters
tac — display starting from the last line. As you can see, tac is cat spelled backwards.
nl — display with line numbers
[root@linux ~]# nl [-bnw] file
Options:
-
-b: how to specify line numbers, two main ways-b a: number all lines, including blank ones-b t: don’t number blank lines
-
-n: how to display the line number, three main ways-n ln: line numbers at the far left of the screen-n rn: line numbers right-aligned in their own field, without leading zeros-n rz: line numbers right-aligned in their own field, with leading zeros
-
-w: the width of the line number field
more — display file contents one page at a time
-
Space: page down
-
Enter: scroll one line
-
/string: search downward for “string” in the displayed content -
:f: immediately show the filename and the current line number -
q: quitmoreimmediately
less — like more, but better: you can page backward too
-
Space: page down
-
[pagedown]: page down
-
[pageup]: page up
-
/string: search downward for “string” -
?string: search upward for “string” -
n: repeat the previous search (with/or?) -
N: repeat the previous search in reverse -
q: quitless
head — show only the first few lines
[root@linux ~]# head [-n number] file
Options:
-n: followed by a number, meaning how many lines to show
tail — show only the last few lines. tail -200f logfile2 (show the last 200 lines of the log)
od — read file contents in binary form
[root@linux ~]# od [-t TYPE] file
Options:
-t: followed by various output “types”, for example:a: output using the default charactersc: output using ASCII charactersd[size]: output in decimal, each integer occupyingsizebytesf[size]: output in floating point, each number occupyingsizebyteso[size]: output in octal, each integer occupyingsizebytesx[size]: output in hexadecimal, each integer occupyingsizebytes
chmod
-
chmod +R filename— add read/write/execute permission;+Rreadable,+Wwritable,+Xexecutable -
chmod 777 filename— another way to add read/write/execute permission (7 = binary 111, read + write + execute)
chown
chown -R haowen . — give ownership of all files and directories under the current directory to haowen; -R includes subdirectories.
chgrp -R mysql . — change the group of a file or directory (changes the current folder to the mysql group; mysql must already exist).
umask — default file permissions
umask specifies the permissions to be subtracted from the default.
chattr — set hidden file attributes
lsattr — show hidden file attributes
find — find ./ -name file1 -print searches downward from the current directory for a file named file1
mkdir — mkdir dir1 creates the directory dir1
mkdir [-mp] directory
Options:
-
-m: set the file permissions directly, ignoring the default (umask) -
-p: create the required directories recursively
[root@linux ~]# rmdir [-p] directory
Options:
-p: also remove the parent “empty” directory
pwd — Print Working Directory (pwd shows the current path). pwd -P shows the real path rather than the one via symlinks.
cd — cd /usr/local/ enters the directory /usr/local/; cd ../ goes up one level
./ is the current directory, ../ the parent, - the previous working directory, ~ the home directory of the current user, and ~account the home directory of the user account. If you type cd alone, it means cd ~.
mv — mv file1 /home/haowen/ moves a file into /home/haowen/ (like cut in Windows); mv file1 filenew1 renames file1 to filenew1
[root@linux ~]# mv [-fiu] source destination
[root@linux ~]# mv [options] source1 source2 source3 .... directory
Options:
-
-f: force; move without asking -
-i: if the destination already exists, ask whether to overwrite -
-u: update — only move if the destination exists and source is newer
cp — cp file1 /home/haowen/ copies a file into /home/haowen/; cp -r dir1 /home/haowen/; cp file1 ./file2 copies and renames
[root@linux ~]# cp [-adfilprsu] source destination
[root@linux ~]# cp [options] source1 source2 source3 .... directory
Options:
-
-a: equivalent to-pdr -
-d: if the source is a link file, copy the link attributes rather than the file itself -
-f: force; copy without asking even if there are duplicates or other questions -
-i: if the destination exists, ask before overwriting -
-l: create a hard link instead of copying the file -
-p: copy the file attributes along with it, rather than using defaults -
-r: recursive copy, used for directories -
-s: copy as a symbolic link, i.e. a “shortcut” -
-u: update the destination only if it’s older than the source
rm — rm file1, rm -r dir1, rm -rf dir2 removes files or directories; f skips the confirmation prompt
[root@linux ~]# rm [-fir] file_or_directory
Options:
-
-f: force; remove without asking -
-i: interactive; ask the user before deleting -
-r: recursive delete, most often used for directories
touch — create an empty file, or update a file’s timestamp to now (mtime and atime)
[root@linux ~]# touch [-acdmt] file
Options:
-
-a: update access time only -
-c: change the time only, without creating the file -
-d: followed by a date; you can also use--date="date or time" -
-m: modify mtime only -
-t: followed by a time in the format [YYMMDDhhmm]
file — if you want to know a file’s basic data, such as whether it’s ASCII, data, or binary, and whether it uses shared libraries, use file to inspect it.
which — finds “executables”. It searches for the executable’s name along the paths defined by the PATH environment variable.
[root@linux ~]# which [-a] command
Options:
-a: list all commands found, not just the first
whereis — find specific files from the database
[root@linux ~]# whereis [-bmsu] file_or_directory
Options:
-
-b: only find binary files -
-m: only find files under the manual path -
-s: only find source files -
-u: files without documentation
wc — count words
Syntax: wc [-clw][--help][--version][filename]
Notes: wc counts a file’s bytes, words, or lines. If no filename is given, or the filename is -, wc reads from standard input. With no options, wc shows lines, words, and bytes together.
Options:
-
-c: show only bytes (characters) -
-l: show only lines -
-w: show only words -
-m: also show characters -
--help: online help -
--version: show version information
locate — list a file’s full path from the database
find ./ -name index.jsp finds files named index.jsp under the current directory.
grep — grep "mobile=13712345678" logfile1 searches logfile1 for the content “mobile=13712345678”
ping — ping 61.129.78.9, ping www.163.com tests whether the network connection works
ifconfig — ifconfig shows the local IP address, subnet mask, and so on
ps — ps aux shows processes already running in the system; ps aux | grep programe1 checks whether program1 is running
kill — kill -9 2325 kills the process with PID 2325; killall programe1 kills the programe1 process
reboot — restart the system
init 0 — shut down (root only)
init 6 — restart the system (root only)
gzip — gzip file1 compresses file1
gunzip — gunzip file1.gz decompresses file1.gz
tar -zcvf — tar -zcvf dir1.tar.gz ./dir1 packs and compresses everything under ./dir1 into dir1.tar.gz
tar -zxvf — tar -zxvf dir1.tar.gz unpacks the archive
echo "hello!" >> file1 — appends “hello” to file1; creates file1 if it doesn’t exist
vi file2 — create the file file2 with the vi editor
…enter the content welcome..
(Press i to enter insert mode; press Esc to leave insert mode. Outside insert mode, dd deletes the current line, x deletes the character under the cursor, and j, n, l move the cursor.)
:wq saves and quits. :q! quits without saving.
Adding environment variables
[root@linux ~]# echo $PATH
[root@linux ~]# PATH="$PATH":/root
env — show some of the system’s environment variables
set — show all of the system’s variables
chmod
Linux/Unix file access permissions are divided into three levels: file owner, group, and others. chmod controls how a file may be accessed by others.
+ adds a permission, - removes one, = sets permissions exclusively. r means readable, w writable, x executable.
- Make file1.txt readable by everyone:
chmod ugo+r file1.txt
or
chmod 444 file1.txt
- Set file2 so the owner can read, write, and execute, while Group and others can only read:
chmod 744 file2 # 7 => "111", 4 => "100" in binary
- Set file3 so the owner can read, write, and execute, while Group and others have no permissions at all:
chmod 700 file3 # 7 => "111", 0 => "000"
Each of a, b, c is a digit representing the permissions of User, Group, and Other respectively.
r=4, w=2, x=1. For rwx: 4+2+1=7. For rw-: 4+2=6. For r-x: 4+1=5.
tar
tar invokes gzip. gzip is a compression program developed by the GNU project; files ending in .gz are the result of gzip compression. The counterpart to gzip is gunzip. tar uses the -z option to call gzip.
# tar -czf all.tar.gz *.jpg
This command packs all .jpg files into a tar archive and compresses it with gzip, producing a gzipped package named all.tar.gz.
# tar -xzf all.tar.gz
This command unpacks the archive produced above.
date — show the date
cal — show a calendar
bc — a simple, handy calculator
[Tab] (pressed twice) — command completion
[Ctrl]-c — interrupt the current program
[Ctrl]-d — end keyboard input (equivalent to typing exit)
info — online help
who — see who is currently online
finger — show information about system users
netstat -a — view network connection status
ntsysv — set which services start at boot
shutdown — shutdown -h now, the usual shutdown command
reboot, halt, poweroff — restart, shut down
System-related commands
-
dmesg: for exampledmesg | moreshows system diagnostic messages, the OS version number, physical memory, and other information -
df: for exampledf -hshows disk space -
du: see the disk space used by each subdirectory -
free: see system memory and virtual memory (swap) size and usage -
top: dynamically view system memory, CPU, and processes in real time
hostname — view the host name
hostname newname — change the host name (temporary; gone after a reboot)
man command — view the basic usage of a command
info command — view the basic usage of a command
ls -l /lib/modules/`uname -r`/kernel/fs
shows which filesystems Linux supports.
cat /proc/filesystems
shows the filesystems currently enabled.
type — query whether a command comes from an external source (not provided by the bash package) or is built into bash
[root@linux ~]# type [-tpa] name
Options:
-
With no options,
typeshows whether that name is an external command or a bash builtin. -
-t: shows the name’s meaning using these words:file: an external commandalias: a name set by a command aliasbuiltin: a bash built-in command
-
-p: if the following name is a command, show its full filename (external) or show it as a builtin -
-a: list all commands containing that name from the paths defined inPATH, including aliases
myname=pqb # set a variable
PATH="$PATH":/home/dmtsai/bin # append to a variable
echo $myname # view a variable
unset myname # unset a variable
Shutting down
Use the shutdown command to close the system, ensuring user and system data stays intact. Only root can use this command; ordinary users aren’t allowed to run it.
First, the syntax:
shutdown [options] when [message]
-
options:
-rmeans reboot,-hmeans halt system services and then shut down immediately,-fmeans a fast reboot -
when: the time for shutdown.
hh:mmis absolute time, hh the hour and mm the minute, e.g. 08:30;+mmeans execute in m minutes;now=+0, i.e. execute immediately -
message: a broadcast message to the system, generally telling each user that the system is shutting down or rebooting and asking them to save their work and log out
Some examples:
shutdown -h now # shut down immediately
shutdown -h 21:30 # shut down at 21:30 today
shutdown -h +10 # shut down in ten minutes
shutdown -r now # reboot immediately
shutdown -r +10 'the system will reboot'
The last one reboots in 10 minutes, with the administrator warning users so they can save their work. Only root can use this command.
Creating files
Creating a file means creating an ordinary, empty file. Use touch:
[root@Linux two]# touch 111.txt
Searching for files
Let’s learn how to search for files. Especially when you’re new to Linux, it happens all the time that you build a file and then can’t remember where you put it. If you know the filename but not which directory it’s in, use locate:
[root@Linux one]# locate install.log
/root/install.log
/root/install.log.syslog
That found two files related to install.log, both under /root. It also feels fast — because this command searches a database. That database is refreshed once every 7 days:
[root@Linux one]# touch 001.txt
[root@Linux one]# locate 001.txt
It can’t find the newly created file, so before searching with this command you have to update the database yourself (updating requires root):
[root@Linux one]# updatedb
[root@Linux one]# locate 001.txt
/root/one/001.txt
After running updatedb, we can find what we need. Updating the database takes a while, though.
locale shows the language environment; the file holding language information is /etc/sysconfig/i18n
/sbin/service xinetd restart|start|stop
starts background services.
/sbin/chkconfig --list |more
shows the startup status of system services, for runlevels 0 through 6. These services are all started by the init system scripts. Some are not started by init — below you’ll see special services that are started by xinetd, a standalone internet server daemon, a super-server that can start many child servers.
As long as the xinetd service is running, the servers beneath it can run. Most of its children are off, with only one on. To turn one on, use chkconfig — for example, to enable rsync: chkconfig rsync on|off.
mount
With no options or arguments, mount shows the currently mounted filesystems in the system.
mount -t type dev dir
The filesystem type for optical discs is iso9660; dev is the device name of the filesystem to mount, and for a CD drive that’s /dev/cdrom; dir is the mount point, the directory path it’s mounted to.
Mounting a CD:
mount -t iso9660 /dev/cdrom /media/cdrom
Listing all storage devices in the system
fdisk -l
Use the “vfat” filesystem type for all FAT filesystem types, including FAT16 and FAT32; NTFS is still represented as ntfs.
Mounting a USB drive:
mount -t vfat /dev/sdb1 /mnt/
mount -t ntfs /dev/sdb1 /mnt/
umount unmounts a mounted filesystem; the basic form is umount dir device
To unmount a CD filesystem, either of these works:
umount /dev/cdrom
umount /media/cdrom
Unmounting a USB drive:
umount /dev/sdb1
eject
eject # eject the disc
eject -t # retract the drive automatically
cut
Usage: all users.
Syntax: cut -cnum1-num2 filename
Description: displays the text from character num1 to num2 of each line.
Example:
shell>> cat example
test2
this is test1
shell>> cut -c0-6 example # the first 6 characters from the start
test2
this i
ln
Usage: all users.
Syntax: ln [options] source dist, where options are:
[-bdfinsvF] [-S backup-suffix] [-V {numbered,existing,simple}] [--help] [--version] [--]
Description: the Linux/Unix filesystem has what are called links, which you can think of as aliases for a file. There are two kinds: hard links and symbolic links. A hard link means one file can have several names; a symbolic link creates a special file whose contents point to the location of another file. Hard links must live in the same filesystem, while symbolic links can cross filesystems.
ln source dist creates a link (dist) to source; whether it’s a hard or soft link is determined by the options.
Neither a hard link nor a symbolic link copies the original file — they only take up a very small amount of disk space.
-f: delete any file with the same name as dist before linking-d: allow the system administrator to hard-link their own directories-i: ask before deleting a file with the same name as dist-n: when making a symbolic link, treat dist as an ordinary file-s: make a symbolic link-v: show the filename before linking-b: back up files that would be overwritten or deleted while linking-S SUFFIX: add SUFFIX to all backed-up files-V METHOD: specify the backup method--help: show help--version: show version
Examples:
Create a symbolic link zz to the file yy:
ln -s yy zz
Create a hard link zz to the file yy:
ln yy xx
at
Usage: all users.
Syntax: at -V [-q queue] [-f file] [-mldbv] TIME
Description: at lets a user run a program or command at a specific TIME. The TIME format is HH:MM, where HH is the hour and MM the minute; you can also use words like am, pm, midnight, noon, or teatime (4 p.m.).
For times more than a day out, use the MMDDYY or MM/DD/YY format, where MM is the month, DD the day, and YY the year. You can also flexibly specify the time as now + interval, where the interval can be minutes, hours, days, or weeks.
You can also use today or tomorrow. Once you specify a time and press Enter, at enters interactive mode and asks for commands; press Ctrl+D when you’re done. The results are mailed back to your account.
Options:
-V: print the version number-q: store in the specified queue.at’s data lives in queues; a user can use several at once, numbered a–z and A–Z, 52 in total-m: send mail to the user even if the program produced no output-f file: read a pre-written command file. You don’t have to type interactively — write everything into a file and read it in at once-l: list all jobs (you can also just useatq)-d: delete a job (you can also useatrm)-v: list jobs that have completed but not been deleted
Examples:
Run /bin/ls at 5 p.m. three days from now:
at 5pm + 3 days /bin/ls
Run /bin/ls at 5 p.m. two weeks from now:
at 5pm + 2 weeks /bin/ls
Run /bin/date at 17:20 tomorrow:
at 17:20 tomorrow /bin/date
Print “the end of world !” at the last minute of the last day of 1999:
at 23:59 12/31/1999 echo the end of world !
cal
Usage: all users.
Syntax: cal [-mjy] [month [year]]
Description: displays a calendar. With a single argument, it’s a year (1–9999) and shows that year’s calendar. The year must be written out in full — cal 89 will not show 1989. With two arguments, they’re the month and year. With no arguments, it shows the current month.
From September 3, 1752 the Gregorian calendar was adopted; since most countries switched then, 10 days were removed, so that month’s calendar is a bit different. Before that it was the Julian calendar.
Options:
-m: display with Monday as the first day of the week-j: display in Julian format, i.e. by day number from January 1-y: display this year’s calendar
Examples:
cal # this month's calendar
[root@mylinux /root]# date
Tue Aug 15 08:00:18 CST 2000
[root@mylinux /root]# cal
...
cal 2001 # the year 2001
cal 5 2001 # May 2001
crontab
Usage: all users.
Syntax:
crontab [ -u user ] file
crontab [ -u user ] { -l | -r | -e }
Description: crontab runs programs at fixed times or intervals — in other words, it’s the user’s schedule. -u user sets the schedule for a specified user, which requires that you have permission (root, for example) to set others’ schedules. Without -u user, you’re setting your own.
Options:
-
-e: open a text editor to edit the schedule; the default editor is VI. To use another editor, set the VISUAL environment variable first (for examplesetenv VISUAL joe) -
-r: delete the current schedule -
-l: list the current schedule
The schedule format is:
f1 f2 f3 f4 f5 program
Where f1 is the minute, f2 the hour, f3 the day of the month, f4 the month, f5 the day of the week, and program the program to run.
- When f1 is
*, the program runs every minute; when f2 is*, every hour; and so on - When f1 is
a-b, it runs from minute a to minute b; when f2 isa-b, from hour a to hour b; and so on - When f1 is
*/n, it runs every n minutes; when f2 is*/n, every n hours; and so on - When f1 is
a, b, c,..., it runs at minutes a, b, c, …; when f2 isa, b, c,..., at hours a, b, c, …; and so on
You can also store all settings in a file first and use crontab file to install the schedule.
Examples:
Run /bin/ls at minute 0 of every hour, every day, every month:
0 7 * * * /bin/ls
In December, every day from 6 a.m. to 12 p.m., every 20 minutes, run /usr/bin/backup:
0 6-12/3 * 12 * /usr/bin/backup
Send a letter to alex@domain.name at 5:00 p.m., Monday through Friday:
0 17 * * 1-5 mail -s "hi" alex@domain.name < /tmp/maildata
At 20 minutes past midnight, 2 a.m., 4 a.m., … every day, run echo "haha":
20 0-23/2 * * * echo "haha"
Note: after a program runs at the time you specified, the system mails you its output. If you don’t want those messages, add > /dev/null 2>&1 after a space at the end of each line.
sleep
Usage: all users.
Syntax: sleep [--help] [--version] number[smhd]
Description: sleep delays the current action for a period of time.
Options:
--help: show help--version: show versionnumber: the length of time, followed by s, m, h, or d, where s is seconds, m minutes, h hours, and d days
Example: show the current time, delay one minute, then show the time again:
date;sleep 1m;date
finger
Usage: all users.
Syntax: finger [options] user[@address]
Description: finger lets a user look up information about other users.
Example — query information about the local administrator:
finger root
last
Usage: all users.
Syntax: shell>> last [options]
Description: shows login information since the system booted, or since the beginning of the month.
Options:
-R: omit the hostname field-num: show the first num entriesusername: show login information for usernametty: limit to login messages containing the terminal name
Example:
shell>> last -R -2
write
Usage: all users.
Syntax: write user [ttyname]
Description: send a message to another user.
Options:
user: the account of the user to messagettyname: if the user has more than one tty connection, choose which to message
Example 1 — message Rollaend, who has only one connection:
write Rollaend
Then type your message; press ctrl+c to finish.
Example 2 — message Rollaend, who has pts/2 and pts/3:
write Rollaend pts/2
Then type your message; press ctrl+c to finish.
Note: if the other user has set mesg n, the message won’t reach them.
expr
Usage: all users.
String length
shell>> expr length "this is a test"
14
Numeric remainder
shell>> expr 14 % 9
5
Grab a substring from a position
shell>> expr substr "this is a test" 3 5
is is
Digit string — only the first character
shell>> expr index "testforthegame" e
2
Reproduce the string literally
shell>> expr quote thisisatestformela
thisisatestformela
clear
Purpose: clear the screen. Usage: type clear at the console.
