Shell Cheat Sheet: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "{{Null/Shell}}")
 
 
(14 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Null/Shell}}
 
==Syntax==
 
A typical shell command might look like this: <code>$ ls -al ~/Downloads/</code>
 
Let’s analyze the above. A command issued follows this pattern:
 
$ command -options arguments
 
* the '''command''' is the name of the program to use
* the '''options''' are the specific settings for the command
* the '''argument''' is what you use the command on
 
==Essential commands==
From https://community.linuxmint.com/tutorial/view/244
=== System Info ===
 
'''date''' – Show the current date and time<br /> '''cal''' – Show this month's calendar<br /> '''uptime''' – Show current uptime<br /> '''w''' – Display who is online<br /> '''whoami''' – Who you are logged in as<br /> '''finger ''user''''' – Display information about '''''user'''''<br /> '''uname -a''' – Show kernel information<br /> '''cat /proc/cpuinfo''' – CPU information<br /> '''cat /proc/meminfo''' – Memory information<br /> '''df''' '''-h''' – Show disk usage<br /> '''du''' – Show directory space usage<br /> '''free''' – Show memory and swap usage
 
=== Keyboard Shortcuts ===
 
'''Enter''' – Run the command<br /> '''Up Arrow''' – Show the previous command<br /> '''Ctrl + R''' – Allows you to type a part of the command you're looking for and finds it
 
'''Ctrl + Z''' – Stops the current command, resume with '''fg''' in the foreground or '''bg''' in the background<br /> '''Ctrl + C''' – Halts the current command, cancel the current operation and/or start with a fresh new line<br /> '''Ctrl + L''' – Clear the screen
 
'''''command'' | less''' – Allows the scrolling of the bash command window using '''Shift + Up Arrow''' and '''Shift + Down Arrow'''<br /> '''!!''' – Repeats the last command<br /> '''''command ''''' '''!$''' – Repeats the last argument of the previous command<br /> '''Esc + . (a period)''' – Insert the last argument of the previous command on the fly, which enables you to edit it before executing the command
 
'''Ctrl + A''' – Return to the start of the command you're typing<br /> '''Ctrl + E''' – Go to the end of the command you're typing<br /> '''Ctrl + U''' – Cut everything before the cursor to a special clipboard, erases the whole line<br /> '''Ctrl + K''' – Cut everything after the cursor to a special clipboard<br /> '''Ctrl + Y''' – Paste from the special clipboard that '''Ctrl + U''' and '''Ctrl + K''' save their data to<br /> '''Ctrl + T''' – Swap the two characters before the cursor (you can actually use this to transport a character from the left to the right, try it!)<br /> '''Ctrl + W''' – Delete the word / argument left of the cursor in the current line
 
'''Ctrl + D''' – Log out of current session, similar to '''exit'''
 
=== Learn the Commands ===
 
'''apropos''' '''''subject''''' – List manual pages for '''''subject'''''<br /> '''man -k ''keyword''''' – Display man pages containing '''''keyword'''''<br /> '''man ''command''''' – Show the manual for '''''command'''''<br /> '''man -t ''man'' | ps2pdf - &gt; ''man.pdf'''''  – Make a pdf of a manual page<br /> '''which''' '''''command''''' – Show full path name of '''''command'''''<br /> '''time ''command''''' – See how long a '''''command''''' takes
 
'''whereis ''app''''' – Show possible locations of '''''app'''''<br /> '''which ''app''''' – Show which '''''app''''' will be run by default; it shows the full path
 
=== Searching ===
 
'''grep ''pattern'' ''files''''' – Search for '''''pattern''''' in '''''files'''''<br /> '''grep -r ''pattern'' ''dir''''' – Search recursively for '''''pattern''''' in '''''dir'''''<br /> '''''command |''''' '''grep''' '''''pattern''''' – Search for '''''pattern''''' in the output of '''''command'''''<br /> '''locate ''file''''' – Find all instances of '''''file'''''<br /> '''find / -name ''filename''''' – Starting with the root directory, look for the file called '''''filename'''''<br /> '''find / -name ”*''filename''*”''' – Starting with the root directory, look for the file containing the string '''''filename'''''<br /> '''locate ''filename''''' – Find a file called '''''filename''''' using the locate command; this assumes you have already used the command '''updatedb''' (see next)<br /> '''updatedb''' – Create or update the database of files on all file systems attached to the Linux root directory<br /> '''which ''filename''''' – Show the subdirectory containing the executable file  called '''''filename'''''<br /> '''grep ''TextStringToFind'' /''dir''''' – Starting with the directory called '''''dir''''', look for and list all files containing '''''TextStringToFind'''''
 
=== File Permissions ===
 
'''chmod ''octal'' ''file''''' – Change the permissions of '''''file''''' to '''''octal''''', which can be found separately for user, group, and world by adding: 4 – read (r), 2 – write (w), 1 – execute (x)<br /> Examples:<br />
'''chmod 777 filename''' – read, write, execute for all<br />
'''chmod 755 filename''' – rwx for owner, rx for group and world<br />
<br />
'''chmod ''symbolic'' ''file''''' – You can also change permissions in '''symbolic''' mode. <br />
Examples: <br />
'''chmod ugo+x filename''' – to make a file executable<br>
'''chmod g+w filename''' – to grant write access to the group<br>
'''chmod o-r filename''' – to remove read access to others
 
u: user
g: group
o: others
 
r: read
w: write
x: executable
 
-R: recursively
 
For more options, see '''man chmod'''.
 
=== File Ownership ===
 
'''chown''' – change ownership
 
'''chown ''name_of_new_owner'' ''filename'''''<br>
'''chown newuser:newgroup filename''' – To change ownership of a file to '''newuser''' and the group '''newgroup'''<br>
'''chown root:www-data /var/www/html/''' – To change ownership of a file to '''root''' and the group '''www-data'''
 
Check the current ownership of a file with: '''ls -l'''<br>
Check which groups you are in with: '''groups'''
 
=== File Commands ===
 
'''ls''' – Directory listing<br /> '''ls -l''' – List files in current directory using long format<br /> '''ls -laC''' – List all files in current directory in long format and display in columns<br /> '''ls -F''' – List files in current directory and indicate the file type<br /> '''ls -al''' – Formatted listing with hidden files
 
'''cd ''dir''''' – Change directory to '''''dir'''''<br /> '''cd''' – Change to home<br /> '''mkdir''' '''''dir''''' – Create a directory '''''dir'''''<br /> '''pwd''' – Show current directory
 
'''rm ''name''''' – Remove a file or directory called '''''name'''''<br /> '''rm''' '''''-r dir''''' – Delete directory '''''dir'''''<br /> '''rm -f ''file''''' – Force remove '''''file'''''<br /> '''rm -rf ''dir''''' – Force remove an entire directory '''''dir''''' and all it’s included files and subdirectories (use with extreme caution)
 
'''cp ''file1 file2''''' – Copy '''''file1''''' to '''''file2'''''<br /> '''cp -r ''dir1 dir2''''' – Copy '''''dir1''''' to '''''dir2'''''; create '''''dir2''''' if it doesn't exist<br /> '''cp ''file'' /home/''dirname''''' – Copy the filename called '''''file''''' to the '''/home/dirname''' directory
 
'''mv ''file'' /home/''dirname''''' – Move the '''''file''''' called filename to the '''''/home/dirname''''' directory<br /> '''mv''' '''''file1 file2''''' – Rename or move '''''file1''''' to '''''file2'''''; if '''''file2''''' is an existing directory, moves '''''file1''''' into directory '''''file2'''''
 
'''ln -s ''file link''''' – Create symbolic link '''''link''''' to '''''file'''''<br /> '''touch ''file''''' – Create or update '''''file'''''<br /> '''cat &gt; ''file''''' – Places standard input into '''''file'''''<br /> '''cat ''file''''' – Display the file called '''''file'''''
 
'''more ''file''''' – Display the file called '''''file''''' one page at a time, proceed to next page using the spacebar<br /> '''head ''file''''' – Output the first 10 lines of '''''file'''''<br /> '''head -20 ''file''''' – Display the first 20 lines of the file called '''''file'''''<br /> '''tail ''file''''' – Output the last 10 lines of '''''file'''''<br /> '''tail -20 ''file''''' – Display the last 20 lines of the file called '''''file'''''<br /> '''tail -f ''file''''' – Output the contents of '''''file''''' as it grows, starting with the last 10 lines
 
=== Compression ===
 
'''tar cf ''file.tar files''''' '''' – Create a tar named '''''file.tar''''' containing '''''files'''''<br /> '''''tar xf file.tar''''' – Extract the files from '''''file.tar'''''
 
'''tar czf ''file.tar.gz files''''' – Create a tar with Gzip compression<br /> '''tar xzf ''file.tar.gz''''' – Extract a tar using Gzip
 
'''''tar cjf file.tar.bz2''''' – Create a tar with Bzip2 compression<br /> '''tar xjf ''file.tar.bz2''''' – Extract a tar using Bzip2
 
'''gzip ''file''''' – Compresses '''''file''''' and renames it to '''''file.gz'''''<br /> '''gzip -d ''file.gz''''' – Decompresses '''''file.gz''''' back to '''''file'''''
 
=== Printing ===
 
'''/etc/rc.d/init.d/lpd start''' – Start the print daemon<br /> '''/etc/rc.d/init.d/lpd stop''' – Stop the print daemon<br /> '''/etc/rc.d/init.d/lpd status''' – Display status of the print daemon<br /> '''lpq''' – Display jobs in print queue<br /> '''lprm''' – Remove jobs from queue<br /> '''lpr''' – Print a file<br /> '''lpc''' – Printer control tool<br /> '''man ''subject'' | lpr''' – Print the manual page called '''''subject''''' as plain text<br /> '''man -t ''subject'' | lpr''' – Print the manual page called '''''subject''''' as Postscript output<br /> '''printtool''' – Start X printer setup interface
 
=== Network ===
 
'''ifconfig''' – List IP addresses for all devices on the local machine<br /> '''iwconfig''' – Used to set the parameters of the network interface which are specific to the wireless operation (for example: the frequency)<br /> '''iwlist''' – used to display some additional information from a wireless network interface that is not displayed by '''iwconfig'''<br /> '''ping''' '''''host''''' – Ping '''''host''''' and output results<br /> '''whois ''domain''''' – Get whois information for '''''domain'''''<br /> '''dig ''domain''''' – Get DNS information for '''''domain'''''<br /> '''dig -x''' '''''host''''' – Reverse lookup '''''host'''''<br /> '''wget ''file''''' – Download '''''file'''''<br /> '''wget -c''' '''''file''''' – Continue a stopped download
 
=== SSH ===
 
'''ssh ''user''@''host''''' – Connect to '''''host''''' as '''''user'''''<br /> '''ssh -p ''port user''@''host''''' – Connect to '''''host''''' on port '''''port''''' as '''''user'''''<br /> '''ssh-copy-id ''user''@''host''''' – Add your key to '''''host''''' for '''''user''''' to enable a keyed or passwordless login
 
=== User Administration ===
 
'''adduser''' '''''accountname''''' – Create a new user call '''''accountname'''''<br /> '''passwd ''accountname''''' – Give '''''accountname''''' a new password<br /> '''su''' – Log in as superuser from current login<br /> '''exit''' – Stop being superuser and revert to normal user
 
=== Process Management ===
 
'''ps''' – Display your currently active processes<br /> '''top''' – Display all running processes<br /> '''kill ''pid''''' – Kill process id '''''pid'''''<br /> '''killall ''proc''''' – Kill all processes named '''''proc''''' (use with extreme caution)<br /> '''bg''' – Lists stopped or background jobs; resume a stopped job in the background<br /> '''fg''' – Brings the most recent job to foreground<br /> '''fg''' '''''n''''' – Brings job '''''n''''' to the foreground
 
=== Installation from source ===
 
'''./configure'''<br /> '''make'''<br /> '''make install'''<br /> '''dpkg -i''' '''''pkg.deb''''' – install a DEB package (Debian / Ubuntu / Linux Mint)<br /> '''rpm -Uvh ''pkg.rpm''''' – install a RPM package (Red Hat / Fedora)
 
=== Stopping &amp; Starting ===
 
'''shutdown -h now''' – Shutdown the system now and do not reboot<br /> '''halt''' – Stop all processes - same as above<br /> '''shutdown -r 5''' – Shutdown the system in 5 minutes and reboot<br /> '''shutdown -r now''' – Shutdown the system now and reboot<br /> '''reboot''' – Stop all processes and then reboot - same as above<br /> '''startx''' – Start the X system
 
= meta characters =
Meta Characters are characters that have special meaning within the terminal
 
* <code>~</code> the tilde stands for '''the user's home'''. <code>cd ~/</code> change directory to home
* <code>/</code> a single forward slash stands for '''root'''. <code>cd /</code> change directory to root
* <code>.</code> dot stands for '''this''' directory. <code>ls .</code> list this directory
* <code>..</code> dot dot stands for '''the parent directory''' to this directory. <code>cp myfile.jpg ..</code> copy myfile.jpg to the parent directory
* <code>*</code> asterisk is a wildcards which represents zero or more characters <code>ls P*.jpg</code> will list all the files, in the current directory, that begin with P and end with .jpg
* <code>\</code> backslash it is a literal character. It escape the meta value of the meta-characters and display them only as literal characters. <code>echo Foo \*</code> will output <code>Foo *</code> If \ wasn't there it would output all the files in that directory.
 
= man pages =
'''man pages are manuals of program.''' They tells you what the program is, what it can do and how.
 
<code>man df</code> show the manual for the program '''df''' that is used to display the free disk space
 
Can you find out how to display the output from df in a human readable format?
 
 
= pipe =
'''A pipes (" | ") sends the output of one program to the input of another program'''.
 
<code>echo "my sentence"| wc</code> the echoed sentence "my sentence" is ''pipped'' into the program wc which counts the number of lines, words, and characters
 
=write=
<code>></code> Writes the output of a command to a file, rather than to print on terminal.
 
<code>df > df_output.txt </code> redirect the content of <code> man dfM </code> to a file called df_output.txt
 
If the said file doesn't exit it will create it, if it already exists it will overwrite its contents/
 
=append=
<code>>></code> appends the output of a command to a file, without overwriting the original file.
<code> echo 'also add this' >> df_output.txt </code> will add 'also add this' to the contents of df_output.txt
 
=package managers=
Package managers like <code>apt-get</code> and <code>aptitude</code> (on Debian/Ubuntu Linux distributions) and Homebrew and MacPorts on Mac, allow more (command-line, but not only) programs, than the ones that come with the operating, to be installed on our system.

Latest revision as of 09:27, 27 September 2022

Syntax

A typical shell command might look like this: $ ls -al ~/Downloads/

Let’s analyze the above. A command issued follows this pattern:

$ command -options arguments
  • the command is the name of the program to use
  • the options are the specific settings for the command
  • the argument is what you use the command on

Essential commands

From https://community.linuxmint.com/tutorial/view/244

System Info

date – Show the current date and time
cal – Show this month's calendar
uptime – Show current uptime
w – Display who is online
whoami – Who you are logged in as
finger user – Display information about user
uname -a – Show kernel information
cat /proc/cpuinfo – CPU information
cat /proc/meminfo – Memory information
df -h – Show disk usage
du – Show directory space usage
free – Show memory and swap usage

Keyboard Shortcuts

Enter – Run the command
Up Arrow – Show the previous command
Ctrl + R – Allows you to type a part of the command you're looking for and finds it

Ctrl + Z – Stops the current command, resume with fg in the foreground or bg in the background
Ctrl + C – Halts the current command, cancel the current operation and/or start with a fresh new line
Ctrl + L – Clear the screen

command | less – Allows the scrolling of the bash command window using Shift + Up Arrow and Shift + Down Arrow
!! – Repeats the last command
command  !$ – Repeats the last argument of the previous command
Esc + . (a period) – Insert the last argument of the previous command on the fly, which enables you to edit it before executing the command

Ctrl + A – Return to the start of the command you're typing
Ctrl + E – Go to the end of the command you're typing
Ctrl + U – Cut everything before the cursor to a special clipboard, erases the whole line
Ctrl + K – Cut everything after the cursor to a special clipboard
Ctrl + Y – Paste from the special clipboard that Ctrl + U and Ctrl + K save their data to
Ctrl + T – Swap the two characters before the cursor (you can actually use this to transport a character from the left to the right, try it!)
Ctrl + W – Delete the word / argument left of the cursor in the current line

Ctrl + D – Log out of current session, similar to exit

Learn the Commands

apropos subject – List manual pages for subject
man -k keyword – Display man pages containing keyword
man command – Show the manual for command
man -t man | ps2pdf - > man.pdf  – Make a pdf of a manual page
which command – Show full path name of command
time command – See how long a command takes

whereis app – Show possible locations of app
which app – Show which app will be run by default; it shows the full path

Searching

grep pattern files – Search for pattern in files
grep -r pattern dir – Search recursively for pattern in dir
command | grep pattern – Search for pattern in the output of command
locate file – Find all instances of file
find / -name filename – Starting with the root directory, look for the file called filename
find / -name ”*filename*” – Starting with the root directory, look for the file containing the string filename
locate filename – Find a file called filename using the locate command; this assumes you have already used the command updatedb (see next)
updatedb – Create or update the database of files on all file systems attached to the Linux root directory
which filename – Show the subdirectory containing the executable file  called filename
grep TextStringToFind /dir – Starting with the directory called dir, look for and list all files containing TextStringToFind

File Permissions

chmod octal file – Change the permissions of file to octal, which can be found separately for user, group, and world by adding: 4 – read (r), 2 – write (w), 1 – execute (x)
Examples:
chmod 777 filename – read, write, execute for all
chmod 755 filename – rwx for owner, rx for group and world

chmod symbolic file – You can also change permissions in symbolic mode.
Examples:
chmod ugo+x filename – to make a file executable
chmod g+w filename – to grant write access to the group
chmod o-r filename – to remove read access to others

u: user
g: group
o: others
r: read
w: write
x: executable
-R: recursively

For more options, see man chmod.

File Ownership

chown – change ownership

chown name_of_new_owner filename
chown newuser:newgroup filename – To change ownership of a file to newuser and the group newgroup
chown root:www-data /var/www/html/ – To change ownership of a file to root and the group www-data

Check the current ownership of a file with: ls -l
Check which groups you are in with: groups

File Commands

ls – Directory listing
ls -l – List files in current directory using long format
ls -laC – List all files in current directory in long format and display in columns
ls -F – List files in current directory and indicate the file type
ls -al – Formatted listing with hidden files

cd dir – Change directory to dir
cd – Change to home
mkdir dir – Create a directory dir
pwd – Show current directory

rm name – Remove a file or directory called name
rm -r dir – Delete directory dir
rm -f file – Force remove file
rm -rf dir – Force remove an entire directory dir and all it’s included files and subdirectories (use with extreme caution)

cp file1 file2 – Copy file1 to file2
cp -r dir1 dir2 – Copy dir1 to dir2; create dir2 if it doesn't exist
cp file /home/dirname – Copy the filename called file to the /home/dirname directory

mv file /home/dirname – Move the file called filename to the /home/dirname directory
mv file1 file2 – Rename or move file1 to file2; if file2 is an existing directory, moves file1 into directory file2

ln -s file link – Create symbolic link link to file
touch file – Create or update file
cat > file – Places standard input into file
cat file – Display the file called file

more file – Display the file called file one page at a time, proceed to next page using the spacebar
head file – Output the first 10 lines of file
head -20 file – Display the first 20 lines of the file called file
tail file – Output the last 10 lines of file
tail -20 file – Display the last 20 lines of the file called file
tail -f file – Output the contents of file as it grows, starting with the last 10 lines

Compression

tar cf file.tar files ' – Create a tar named file.tar containing files
tar xf file.tar – Extract the files from file.tar

tar czf file.tar.gz files – Create a tar with Gzip compression
tar xzf file.tar.gz – Extract a tar using Gzip

tar cjf file.tar.bz2 – Create a tar with Bzip2 compression
tar xjf file.tar.bz2 – Extract a tar using Bzip2

gzip file – Compresses file and renames it to file.gz
gzip -d file.gz – Decompresses file.gz back to file

Printing

/etc/rc.d/init.d/lpd start – Start the print daemon
/etc/rc.d/init.d/lpd stop – Stop the print daemon
/etc/rc.d/init.d/lpd status – Display status of the print daemon
lpq – Display jobs in print queue
lprm – Remove jobs from queue
lpr – Print a file
lpc – Printer control tool
man subject | lpr – Print the manual page called subject as plain text
man -t subject | lpr – Print the manual page called subject as Postscript output
printtool – Start X printer setup interface

Network

ifconfig – List IP addresses for all devices on the local machine
iwconfig – Used to set the parameters of the network interface which are specific to the wireless operation (for example: the frequency)
iwlist – used to display some additional information from a wireless network interface that is not displayed by iwconfig
ping host – Ping host and output results
whois domain – Get whois information for domain
dig domain – Get DNS information for domain
dig -x host – Reverse lookup host
wget file – Download file
wget -c file – Continue a stopped download

SSH

ssh user@host – Connect to host as user
ssh -p port user@host – Connect to host on port port as user
ssh-copy-id user@host – Add your key to host for user to enable a keyed or passwordless login

User Administration

adduser accountname – Create a new user call accountname
passwd accountname – Give accountname a new password
su – Log in as superuser from current login
exit – Stop being superuser and revert to normal user

Process Management

ps – Display your currently active processes
top – Display all running processes
kill pid – Kill process id pid
killall proc – Kill all processes named proc (use with extreme caution)
bg – Lists stopped or background jobs; resume a stopped job in the background
fg – Brings the most recent job to foreground
fg n – Brings job n to the foreground

Installation from source

./configure
make
make install
dpkg -i pkg.deb – install a DEB package (Debian / Ubuntu / Linux Mint)
rpm -Uvh pkg.rpm – install a RPM package (Red Hat / Fedora)

Stopping & Starting

shutdown -h now – Shutdown the system now and do not reboot
halt – Stop all processes - same as above
shutdown -r 5 – Shutdown the system in 5 minutes and reboot
shutdown -r now – Shutdown the system now and reboot
reboot – Stop all processes and then reboot - same as above
startx – Start the X system

meta characters

Meta Characters are characters that have special meaning within the terminal

  • ~ the tilde stands for the user's home. cd ~/ change directory to home
  • / a single forward slash stands for root. cd / change directory to root
  • . dot stands for this directory. ls . list this directory
  • .. dot dot stands for the parent directory to this directory. cp myfile.jpg .. copy myfile.jpg to the parent directory
  • * asterisk is a wildcards which represents zero or more characters ls P*.jpg will list all the files, in the current directory, that begin with P and end with .jpg
  • \ backslash it is a literal character. It escape the meta value of the meta-characters and display them only as literal characters. echo Foo \* will output Foo * If \ wasn't there it would output all the files in that directory.

man pages

man pages are manuals of program. They tells you what the program is, what it can do and how.

man df show the manual for the program df that is used to display the free disk space

Can you find out how to display the output from df in a human readable format?


pipe

A pipes (" | ") sends the output of one program to the input of another program.

echo "my sentence"| wc the echoed sentence "my sentence" is pipped into the program wc which counts the number of lines, words, and characters

write

> Writes the output of a command to a file, rather than to print on terminal.

df > df_output.txt redirect the content of man dfM to a file called df_output.txt

If the said file doesn't exit it will create it, if it already exists it will overwrite its contents/

append

>> appends the output of a command to a file, without overwriting the original file. echo 'also add this' >> df_output.txt will add 'also add this' to the contents of df_output.txt

package managers

Package managers like apt-get and aptitude (on Debian/Ubuntu Linux distributions) and Homebrew and MacPorts on Mac, allow more (command-line, but not only) programs, than the ones that come with the operating, to be installed on our system.