Getting Started with Bash
This is a beginner-oriented post intended to get you comfortable using your *nix-based operating system’s command line for common tasks. More advanced features will be the topic of future posts.
The command line is a great way to quickly and efficiently work with files, and sometimes it’s the only way to accomplish certain tasks. Being able to use the command line to quickly create and modify files is essential for developers in nearly every field.
If you’re not already familiar with BASH (Bourne-Again SHell), this post is meant to get you started navigating your computer from the command line. I cover some basic commands and shortcuts here, but you’ll want to experiment on your own and follow the links I provide at the bottom if you would like to take on more advanced tasks.
If you want to follow along, open up your terminal on macOS or any flavor of Linux (I can’t guarantee these commands will work with Windows Powershell. Also, keep in mind that only Windows 10 has a BASH shell).
Some Basic Commands
There are a handful of bash commands you will use often, so let’s get familiar with them right off the bat.
pwd
— You can print the directory you are in using pwd (print working directory)ls
— View the contents of your current directory with ls. You can view a long-form list withls -l
or view hidden files withls -a
. If you want to see what’s in a different directory, provide that directory’s path as the first argument to thels
command.touch
— You can create a file using touch:touch file
and if you typetouch file
again, the date/time modified for that file will be updated to the time you touched it.echo
— Start interacting with the terminal by printing to standard output using echo:echo "Hello"
. You can also use echo to write to file like this:echo "Some random text" > file2
, which will both create the file for you and write to it. If you try this again, it will overwrite your previous text. If you would like to to append text to this file, you will need to use » like this:echo "Some more text" >> file2
.cat
— If you would like to take a look at the file you just wrote to, typecat file2
.ctrl + r
— Search commands previously used
To practice using these commands, you can follow these steps in your interpreter:
- Open your command line interpreter and print your working directory to get oriented
- List the contents of the directory you’re in
- Create a few new files and then list the contents of your directory again
- Type “hello world” or something equally silly to standard output
- Write some text to a file and look at the file’s contents in the terminal
- List files using long (
-l
) argument, touch an existing file, then list files again to see changes to the last time modified
Working With Directories
cd
is the command used to change directories. It takes one parameter - the absolute or relative filepath you would like to move to (cd with no parameters takes you to your home directory).
- Navigate to your home directory
cd
orcd ~
- Navigate to a specific directory
cd path/to/my/directory
orcd my_directory
- Navigate up a level
cd ..
- Navigate up more than one level
cd ../..
- Navigate to previous directory
cd -
mkdir
— Make a new directorymkdir directory_name
rmdir
— Delete an empty directoryrmdir directory_name
- Delete a directory and its contents
rmdir -rf directory_name
- List subdirectories
ls -d */
Practice these commands by following along:
- Move to your home directory and print the directory name
- List the contents of your home directory and move to a subdirectory
- Move back to where you were (home directory) and list all subdirectories
- Navigate to a directory several folders deep, then return using the absolute path of your home directory
- Create a subdirectory “new_dir” and delete it. Check that it’s gone by listing out the parent directory contents
- Create a subdirectory “my_dir” and add files or folders to it, then delete it
Working with Files
Although files and directories are technically the same thing in *nix operating systems, some different commands are used for working with files.
less
andcat
— Read a file with lessless file.txt
or catcat file.txt
Less is a file reader that returns a single screen at a time and allows the user to scroll through the file. Cat is short for concatenate, and outputs results to standard output, and it can be used to quickly view the contents of files as long as you don’t need to scroll.>
— Empty a file without deleting it> file.txt
rm
— Remove a filerm file.txt
or all filesrm *
mv
— Move a filemv file_name directory_name
You can also use mv to rename a file or directory like this:mv file.txt file2.txt
. If you’d like to batch rename files, use rename:rename –v 'dir/file/path/' *
cp
— Copy a filecp file_name directory_name
open
— Open a file using the default program withopen file.txt
or with a specific programprogram_name open file.txt
(eg.nano open file.txt
). You can can also simply open a program by typing in the program name like this:chrome
. You’ll need to make sure the program is already in your $PATH variable by editing your profile (typically located in /etc/profile). You can check your path variable by typingecho $PATH
.
Text Editors — Vim, Emacs, Nano, Pico
Linux and Unix provide an abundance of useful text editors, each of which is extremely feature-rich. I can’t tell you which ones are best, but I like using Vim. Beginners will likely appreciate the ease of getting started with nano or Emacs.
nano
orpico
— Edit a file usingnano filename
orpico filename
. Nano is a clone of Pico and both have similar functionality.vi
orvim
— Opening a file for editing in Vimvi file.txt
orvim file.txt
Vi is a text editor created in the 1970s for Unix and was cloned and augmented in 1991, resulting in Vi IMproved (VIM). It’s a bit tricky to learn, but once you do, you’ll likely be hooked. It’s quite powerful and extensible. Follow the official tutorial to get started with Vim. Just remember, to close Vim you will need to be in edit mode (hit escape if you aren’t) and type:q!
to quit without changes or:wq
to write changes to file and quit (SHIFT-z-z does the same thing).emacs
— Files can be opened in GNU Emacs in the same way as Vim or Nanoemacs file.txt
. Emacs is another text editor, which I have yet to use much. There are many people who love it, and it has some additional functionality that Vim doesn’t have by default, so it might be worth checking out.
If you would like to try these commands out for yourself, follow along:
- Create a file “my_file” and type or paste in some text. Hipster Ipsum is a good source for nonsense text
- Use less and cat to read to the file’s contents. Empty the file you created, then delete it
- Create a new file “file.txt” and rename it to “file1.txt”
- Create several text files, then rename them using rename
- Open one of these files from the command line using your IDE of choice. Type in some text then save and close
- Reopen the last file using nano or pico and modify it
- Reopen the last file again using Vim or Emacs, make some changes (to make changes in Vim, you’ll need to switch to insert mode by typing i and ESC to go back to command mode) and exit
- Play around by adding hipster ipsum text to each of the files you created and cat the results to standard output
Shortcuts for Working With Text
There are a few handy shortcuts that will save you a lot of time and energy in the command line.
ctrl-A
— Move to beginning of current linectrl-E
— Move to end of current lineAlt-b
— Moves back one wordAlt-f
— Moves forward one wordCtrl + u
— Cut everything before the cursor to the clipboardCtrl + k
— Cut everything after the cursor to the clipboardCtrl + y
— Paste from the clipboard thatCtrl + u
andCtrl + k
save their data toCtrl + t
— Swap the two characters before the cursorCtrl + w
— Delete the word to the left of the cursorCtrl + l
orclear
— Clear the screen
Searching
There are a ton of handy ways to search using the command line, which I can almost guarantee will come in super handy at some point
find
— Find a filefind . –name "*.txt"
locate
— Find a directory using locatelocate directory_name
grep
— Find a text string in filesgrep -Pri search_term filepath/file.txt
egrep
— Search text and return lines that match a patternegrep [command line options] <pattern> [path]
For practice searching, try these steps:
- Search for one of the files you created previously using find
- Search for a directory you know exists
- Search for for some of the hipster ipsum you previously pasted using grep and egrep
Multiple Commands and Command Reuse
You can also string commands together on a single line, either separately or in conjunction
- In a single line
command1; command2; command3
- Run commands together
command1 && command2
!$
— Reuse last item (eg.cd !$
orecho !$
)!!
— Reuse previous commandsudo !!
(history
also shows the history of commands used)- Loop over a set of files using a for loop
for f in *.txt; do echo "some text"; done
Getting Help
Bash provides extensive documentation for each all commands, all of which can be accessed from the command line
help
— Finding out how to use a commandcommand --help
man
— Finding manual pagesman
orman command
- Search man pages using a keyword
man -k search_term
Other Topics
This was a super brief and superficial orientation to the command line. There is a ton more to learn. In a future post, I will cover some more super handy shell features, including:
- Redirection/Piping
- Using SHELL Scripts
- Aliases
- Working with Permissions
- Filters
- Process Management
- Regular expressions
Useful Links
- Codecademy’s List of Command Line Commands
- Bash Shortcuts
- Ryan’s Tutorial’s Cheat Sheet
- Free Code Camp Post on the Command Line
Originally published at danstrong.tech.