0% found this document useful (0 votes)
5 views11 pages

Basic Linux Commands

This document provides a comprehensive guide to essential Linux commands, including how to pipe, concatenate, and manage files and directories. It also covers background processes, user management, and basic Git commands for repository initialization and file management. The commands are explained with examples to assist users in effectively utilizing the Linux command line and Git.

Uploaded by

quark380
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Basic Linux Commands

This document provides a comprehensive guide to essential Linux commands, including how to pipe, concatenate, and manage files and directories. It also covers background processes, user management, and basic Git commands for repository initialization and file management. The commands are explained with examples to assist users in effectively utilizing the Linux command line and Git.

Uploaded by

quark380
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Linux commands for Jonah.

How to pipe and concatenate:

$ cat > filename.txt


Create a new file with name filename.txt, and put whatever you type on standard input
into it. Note: If filename.txt already exists, this method deletes whatever is in it.

$ cat >> filename.txt


Append standard input to the end of existing file filename.txt

$ cat filename.txt | grep “example”


Search filename.txt for the string “example”. it will print the location of the string to
standard output

$ echo “hello world” > hello.txt


Create a new file hello.txt, and write the string “hello world” into it

$ echo “normal command” > /dev/null


This command discards what would normally appear on standard output. So the echo
command doesn’t print anything.

$ badcommand 2> /dev/null


This command doesn’t exist, so normally the shell would print “command not found”.
The bit “2>” redirects standard error. So this line does not print anything.

$ cat longfile.txt | head -n 5


Print the first 5 lines of “longfile.txt”.

$ cat longfile.txt | tail -n 5


Print the last 5 lines of “longfile.txt”.

How to fork:

$ tar cvzf big_archive.tar.gz big_directory &


Note the ampersand. Type an ampersand after a command to run it in the background.
A typical “tar” command with a lot of files will take a long time, and you wouldn’t be
able to continue to run commands without an ampersand. This method prints out the
PID (process ID).

At this point, you can type “fg” to bring this process to the foreground.

Linux Help Page 1 of 11 your friend Tanner Babcock


Commands:

Remember: When typing a command, the space character “ “ is used to


separate arguments. Because of this, filenames that have spaces in them must
be wrapped in double-quotes or have each space escaped individually with a
backslash (‘\’).

Bad: $ cat Filename With Spaces.txt

Using the above example, the shell would try to open three separate files: “Filename”,
“With”, and “Spaces.txt”, none of which exist. The example below only has one
argument, instead of three, and it only looks for one file.

Good: $ cat “Filename With Spaces.txt”

Good: $ cat Filename\ With\ Spaces.txt

cd [directory] - Change current directory

ls [directory] - List files in the specified directory, or current directory if none


provided

echo [string] - Print string on stdout

nano [file] - Edit file in Nano text editor. Easy for beginners. The controls are
visible on the screen while editing. Press Control + X to quit. Control + W will write the
current buer. Control + K cuts the current line, Control + U pastes. Control + C will tell
you the current cursor position. Control + W lets you search for a string.

vim [file] - Edit file in Vim text editor. Intermediate text editor, use when you get
good with Nano. Type “:q” in command mode to quit. “:wq” (that’s with a colon) will
write the file, and then quit. “:w “, and then a filename, will write the current buer to a
new file. Always press “i” to toggle insert mode, and then press Escape when you’re
done typing.

touch [file] - Create a new empty file

tar xvf [name of archive] - Decompress .tar or .tar.gz archive file

tar cvzf [output filename] [file or directory to compress] -


Compress a file or directory into a .tar.gz archive

Linux Help Page 2 of 11 your friend Tanner Babcock


gzip -d [archive.gz] - Decompress a Gzip format archive

gzip -c [file name] > output.gz - Compress a single file

mv [source] [destination] - Move or rename source file to new filename, or


existing directory

Example: $ mv old_file.txt new_file.txt

Renames “old_file.txt” to “new_file.txt"

Example: $ mv file.txt path/to/directory

Moves “file.txt” into “path/to/directory”, keeps filename.

cp [existing file] [new filename] - Copy an existing file

cp -r [existing directory] [new directory] - Copy an entire


directory

rm [unwanted file] - Delete a file

rm -rf [unwanted directory] - Delete an entire directory

mkdir [name] - Create new directory with specified name

rmdir [name] - Remove an empty directory

sudo [command] [arguments] - Run command as root / superuser

Note: If you try to do something and get a “Operation not permitted” error, that
means your user doesn’t have the required permissions. Run the exact same
command with “sudo” before it. You will be prompted for the root password.
As a shortcut, you can just type sudo !! to repeat the previously typed
command.

man [command] - Open the manual page for the specified command. Interactive
program. Press “q” to quit.

which [command] - Show the path to the specified command

Linux Help Page 3 of 11 your friend Tanner Babcock


chmod +x [filename] - Give executable permissions to the specified file. You
will have to do this if you write a shell script. The command chmod 755
[filename] does the same thing.

chown [username]:[user group] [filename] - Change ownership of


specified file or directory

chgrp [new group] [file] - Change the owning group of the specified file.
The default group for your typical user is most likely the same as your username. “

kill [PID number] - Kill a process, given a PID (process ID) number. You can
use the “top” command or ps -a to retrieve the PIDs.

killall [name of process] - Kill all processes with the specified name.

pwd - Self-explanatory: Stands for “print working directory”. The environment


variable $PWD tells you the same thing.

top - Interactive program. Lists all of the currently running processes, with PIDs,
CPU usage, and memory usage. Press “q” to quit.

ssh [username]@[IP address or domain name] -p [port] -


Connects to a remote host. This can be another computer, a Raspberry Pi, an Android
phone, a website or a server. For example, this is how I log into my own website:

$ ssh [email protected] -p 2222

This command will prompt you for the password when you connect. It is possible to
use ssh without having to type a password, but this is an advanced topic.

scp [file] [username]@[domain or IP]:[target directory] -


Send the specified file to the target computer over SSH. This will prompt for the target
user’s password, and it will place the given file in the target directory.

eval $(ssh-agent) - Start the SSH agent in the background. This program is in
charge of holding and exchanging private and public SSH keys

ssh-keygen -t rsa -f [output file] - Generate a public and private


RSA key files. This will prompt to enter a passphrase, and will produce a
fingerprint.

mount [device file] [mount point] - Mount the device file to the
specified directory. Every external drive (USB, iPod, external hard drive) has a device

Linux Help Page 4 of 11 your friend Tanner Babcock


file in the /dev directory. Your internal hard drive is usually at /dev/sda1 or /dev/
sda2. The external hard drive or USB device is usually at /dev/sdb1 or /dev/
sdb2.

Example: $ mount /dev/sdb2 /mnt/iPod

umount [mount point] - Unmount a previously-mounted drive. Use the same


directory you used for the mount command.

Example: $ umount /mnt/iPod

whoami - Print the current user’s name. This is also in the environment variable
$USER.

cal [year] - Print a calendar for the specified year, or the current month if no
arguments

date - Print today’s date and time

df -h - Show disk usage and remaining free space on all mounted drives

dd if=[input file] of=[output file] - Stands for “data duplicate”. Use


this command to format a device, or flash an ISO or IMG to a device file. This will
delete all data in the output file.

fsck - Check the hard drive for problems

export [variable name]=“variable content” - Create an


environment variable with specified content

id [username] - Show all of the groups that specified user belongs to

ifconfig - List all network interfaces

find [directory] - List all files recursively in the given directory

ping [domain or IP] - Send TCP packets to specified domain or IP to test its
responsiveness

[command with long output] | less - Interactive pager. Use this to scroll
up and down to read a command or a file with a lot of text. Press “q” to quit.

Linux Help Page 5 of 11 your friend Tanner Babcock


md5 - Calculate MD5 hashes of strings or files

gpg —-encrypt [input file] —-output [output file] - Encrypt a file


using default key. Output file should end in “.gpg”

gpg —-decrypt [encrypted file] > [decrypted output] - Decrypt a


previously-encrypted file

useradd - Create a new user, or add a user to groups. Only works with root or
“sudo”.

usermod - Modify user details. Only works with root or “sudo”.

systemctl [action] [service] - “Action” should be either “start”, “stop”,


“restart”. This is a SystemD utility for starting and stopping services. This will only work
on SystemD Linux distros (the majority).

time [command] - Run the specified command, and show the amount of time
used for execution afterwards.

pushd [directory] Change to the specified directory. This command adds the
new current directory to the “stack” of directories in the shell. This means that when
you “popd”, you will return to your initial directory.

popd [directory] Pop the directory from the “stack”, and return to the initial
directory. Both “pushd” and “popd” will echo all directories in the stack.

curl [URL] > outputfile Fetch the HTML content (or image, or whatever file
type) used as the response at the specified URL, and save in outputfile.

wget [URL] Retrieve the specified URL, same as Curl.

cmp [one file] [other file] - Compare the two files. What this means is,
return 0 “success” if the two files are exactly the same, or return 1 “error” if the two
files are dierent. This command will tell you where the first dierence is. The return
code of any command can be looked at with the variable $?

read [new variable] Read the first line of user input into the new environment
variable with the specified name. For example, “read foobar; echo $foobar”
will wait for user input, and then repeat that same string. This is useful in shell scripts.

sleep [number of seconds] Pause the shell for specified number of seconds.

Linux Help Page 6 of 11 your friend Tanner Babcock


false - Always returns the error code 1, “error”. “1” is interpreted by the shell
to mean the executed command failed.

true - The same for the opposite. This always returns “0”, in every circumstance. 0 is
interpreted by the shell as “success”. “true” and “false” can be placed at the end of
shell scripts to signal an error.

ln -sF [existing file to be referenced] [name of link] Create


a symbolic link. Symbolic links are essentially “shortcuts”, tiny files that point to other
files. You can create a symbolic link to a directory, and that will behave like a separate
place, but parallel to the original. The symbolic link will apply all changes you apply to it
to the original file!

make [operation] - Run GNU Make on a Makefile. You will need this if you ever
compile someone else’s C or C++ program. For example, when compiling the Linux
kernel, you will type these things:

Example: $ make menuconfig


— interactive menu -
$ make -j2

When running make, the option “-j” will specify how many parallel jobs to run. Ideally,
you should run as many parallel jobs as you have processor cores, but you can do
more than this. Anyway, in the case of the ocial Linux kernel, this command would
take a very long time. Like, eight or nine hours on a normal computer. However, a
smaller application, can only take a few seconds to compile completely with the make
command.

With common application software, the “make” command is usually preceded by


running the configure script ( ./configure ). If this command succeeds, and you
have all of the compile-time dependencies, it will generate a Makefile and you can run
Make.

wc [filename] Word counter. This command tells you how many lines, words, and
bytes are in any given file, respectively.

pgrep [process name] Print the Process ID of the process with the given name.

expr [math operation] Do some quick math. For example, “expr 5 + 2” will
print “7”.

Linux Help Page 7 of 11 your friend Tanner Babcock


sudo apt-get install [package] - Install anything you need on Ubuntu or
any other Debian-based distro. On Red Hat, this command is sudo yum install
[package]. This is the fundamental dierence between the Linux distributions.

sudo apt-get remove [package] - Removes an unwanted package. A good


package manager will tell you if removing this package will break others that
depend on it.

sudo apt autoremove - Here’s a good one for Debian/Ubuntu. This command
detects obsolete and unused packages, and oers to remove them. It will tell you how
much disk space it is saving.

Git for Newbs

Alright listen up boys. If you are working in this field, you’re going to be using git at
some point. Either a little bit or a lot, whether you’re just cloning, or committing,
merging, and pulling, you’re going to be using this: And you need to know what you’re
doing. This is a very quick guide on simple git tasks for the newcomer. I was really lost
using git for several years, and wish I had a comprehensive guide. Really the interface
is quite simple if you learn to visualize it.

How to create and initialize a bare repository (i.e. a directory) for a site like GitHub:

$ mkdir my-cool-thing
$ cd my-cool-thing
$ git init
Initialized empty git repository
$ touch myFile.js
$ cat > README.md # README.md will appear on GH
# My Cool Thing

Hey everyone, this is *my* cool thing.


$ git add myFile.js
$ git add README.md
$ git remote add origin https://github.com/you/example.git
$ git commit -m “Initial commit”
[f73ed8 Initial commit]
12 Additions, 0 Deletions
$ git push origin master
Your username for GitHub.com: you
Password:
Resolving deltas. . . 8/10. . . 28kB/S

Linux Help Page 8 of 11 your friend Tanner Babcock


Updating files. . .
Pushed: master -> github.com/you/example.git

What this sequence of commands does is: It creates a new directory, with two files
inside of it. “myFile.js” and “README.md”. It initializes an empty repository. These files
are added to the staging area.

The GitHub repository URL is added as the remote “origin”: the default global URL.
This needs to be done before anything can be pushed. The typical commit message for
the first commit is “Initial commit”. What “git push origin master” means, is: You are
pushing to the master branch of the origin global location.

git init - Initialize an empty git repository in the current directory. This creates an
invisible directory “.git”, which is present in every repository.

git remote add origin [the repository URL] - This line is very
important when creating a new project in version control. GitHub for example
(remember Git is not necessarily the same thing as GitHub), will give you a URL that
looks like this: https://github.com/Jonah/your-repo.git

git add [file or directory] - Add a newly changed file or directory to the
staging area. The staging area is the hypothetical place where files have been selected
for committing. Just because you change a file, does not mean your changes have
been staged. Adding a directory, like git add . will automatically add all of the
changed files in that directory.

git rm [unwanted file] - Removes the file from the repository, and actually
deletes it. The only way to restore a file deleted this way is with git checkout or
git reset —-hard .

git rm -r [unwanted directory] - Does the same for an entire directory.


The “-r” option can be assumed to make the command operate recursively: through a
whole directory and its sub-directories. This is true for the real commands rm, cp,
chown, etc.

git rm —-cached [retracted file] - This is like safe mode “git rm”. This
deletes the file from the repository, but retains the actual file. This adds the “rm”
change to your current staged changes.

git status - Your best friend. This command tells you all unstaged and staged
changes for the repository, since the last commit. Staged changes are in green,
unstaged changes are in red.

Linux Help Page 9 of 11 your friend Tanner Babcock


git checkout [branch or commit] -- [specific file] - This
command allows you to browse the Git repository as it appeared at a specific commit
in time. You can get a list of commit hashes (those 6-digit hexadecimal numbers) from
the git log command. You can check out the whole repository, or simply look at an
individual file with the “- - filename.txt” syntax. For example, if a repository has a
branch called “dev”, you would do git checkout dev. Or, if you’ve tracked that
something important happened at commit d832ab, you can also type git checkout
d832ab

git checkout -b [new branch name] - Create a new branch and switch to
it.

git commit -m [commit message] - This is the command that writes your
staged changes in stone, for all future programmers. Committing saves all of your
saved changes and then waits to be pushed. You can commit several times before you
push, and all of the commits will send at once. Make sure your commit message is
always enclosed in “quotes”.

When you commit for the first time, you will possibly be prompted to add information
about yourself: Your name and email address. This information is saved in
~/.gitconfig. Your name and email are pretty much what associate you with your
commits, and your GitHub will automatically link your profile if you’re committing with
the same email address.

git reset —-hard [remote]/branch - This is the command that saves your
ass if you ever fuck up a repository so much, that you just want to abandon all of your
changes and set it back to how it was. The command in this situation is usually git
reset —-hard origin/master.

git push [remote] [branch] - Push (globally publish) the locally-saved


commits to the global repository. This command is usually git push origin
master, but can also be something like git push upstream dev. When and if
you create a new branch for yourself and start committing to it (a very powerful
development strategy anywhere), you will have to modify your “git push” command.
Oh, and these commands are optional. After pushing in the long form at least once,
git push will probably assume the remote is “origin” and the branch is “master”, or
whatever was last used. The same is true for the “git pull” command.

git pull [remote] [branch] - Pull (retrieve the latest commits) and
synchronize your local repository. This command always gives you a colorful summary
of which files were changed, and how many additions and deletions there were.

Linux Help Page 10 of 11 your friend Tanner Babcock


git remote (set-url, get-url, add, remove) [name of remote
location] [repository URL] - Add, remove, set a new URL, or retrieve the
existing remote URL.

Obvious Things That Will Help

The key code Control + C will, in usual circumstances, cancel the currently running
operation due to a SIGINT signal. Even if you’re in the middle of a “tar” or “dd” or
“usermod”, Control + C will pretty much stop that process.

Control + L can be pressed at almost any time to clear the screen. The shell prompt will
re-appear at the top. If you press Control + L in the middle of a command, the shell will
clear when that command is done. You can also simply type “clear”.

In Bash, the default shell in most Unix and Linux systems, when typing a filename, you
can press the TAB key to show a list of possible matches. The shell will show you the
possible matches below the command line. In Z Shell, this is an interactive menu.

Linux Help Page 11 of 11 your friend Tanner Babcock

You might also like