Useful BASH Commands

In an earlier post, I’ve covered keyboard shortcuts for Bash, the Unix shell (aka the terminal). In this post I’ll try to list all the Bash commands I’ve found useful. I refer to this list on a regular basis, so if you find errors or have something to add, please post a comment. Note that some of these need to be run with elevated privileges (preceded by “sudo”), but I’ve left off the sudo.

GNOME Terminal

BASH Commands

!!
Repeat the last executed command. Usually, you do this if you forgot to say “Simon Says” (meaning you forgot to precede the command with “sudo”). The only time I use this is to do: sudo !!
./
This is good to know. If you’ve just navigated to a directory in the shell and want to open a file or application from where you are, you can’t just type the name. You have to use this command first. It’s like saying, “Yes, I meant this damn directory!”
\
Escape operator. Use it before a space if you’re trying to open a file that has whitespace in the name.
&
Ampersand is a built-in control operator used to form processes. If a command is terminated by &, the shell executes the command in the background in a subshell. When this happens, you can see the child process by using jobs; you can see the child PID by using echo $$; and you can kill the job by using kill %1, assuming that 1 was the job number.
&&
This is the AND control operator. If you have command1 && command2, then command2 is only executed if command1 returns an exit status of zero.
|
This is the pipe control operator, for which Unix is famous. I usually pipe long output to the pager program called “less” as in ls -a | less
||
This is the OR control operator. If you have command1 || command2, then command2 is only executed if command1 returns a non-zero exit status.
:
The colon is a built-in command used for “expanding arguments and performing redirections”. I’ve noticed it is used to separate lists of items in the environmental variables (see yours with the command env).
~
The tilde represents your home directory.
Characters enclosed in single quotation marks are not interpreted by BASH, so that variables (represented with a preceding dollar sign as in $VAR) are not expanded: echo ‘$USER’ prints $USER while echo “$USER” prints greeenguru (for me anyway) just as would echo $USER
Characters enclosed in double quotation marks ARE interpreted by BASH, so that variables (represented with a preceding dollar sign as in $VAR) are expanded. See the discussion about single quotes versus double quotes above. This means that you need to be purposeful when using the dollar-sign, back-tick (`), and backslash inside double quotes. Additionally, I’ve had problems representing the exclamation mark inside double quotes.
$()
This is the best syntax for command substitution, which is a method of treating the output of a command as if it were written on the command line itself. Here’s an example: echo “The date is: $(date +%D)” will print The date is: 06/07/10 to the console.
`
This is an old (an inferior) syntax for command substitution (see demonstration of the better method using $() above). Example: echo “The date is: `date +%D`”
>
This is the standard redirection operator, which takes output that would normally be directed to the console and writes it to a file instead. An example would be: echo ‘Hello World’ > hello.txt, which would create (or overwrite) a file named hello.txt to the current directory and place the text “Hello World” inside. > is actually shorthand for 1>, which means to direct stream 1 (stdout) to the file specified.
>>
This redirection operator works just like > except it will append to an existing file rather than overwriting it
2>
This is the standard error redirection operator, which takes error output that would normally be directed to the console and writes it to a file (or another device) instead. An example would be: ls a 2> hello.txt, which would create (or overwrite) a file named hello.txt to the current directory and write to it the error output from the mis-typed command “ls a” (should have been ls -a). More commonly, people use this redirect to silence error output by telling it to go hell (to the null device) as in ls a 2> /dev/null
2>&1
This redirection operator combines stdout (stream 1) and stderror (stream 2) streams. To demonstrate its use I’ll use a command that produces both kinds of streams: ls . a, which lists the contents of the current directory but then produces an error when it gets to “a” because there is “No such file or directory”. Here’s how you would direct both the stdout and stderror output of this command to a file: ls . a > text.txt 2>&1 It is counterintuitive to combine the streams at the end, but that’s how you have to do it: redirect stdout and THEN combine stderror to it. Check out this explanation.
apropos <subject>
Returns a list of commands related to the subject
apt-cache search firefox | grep plugin
Search for available firefox packages with “plugin” in the description. This is a handy way to search for a package if you can’t remember its name
apt-get update
Check repositories for an update to installed software using the package management utility apt-get. You usually run this after you add a new repository. You need elevated permissions to run this (sudo).
batch <command>
Run any command when the system load is low
cal 2009
Display a year calendar for 2010 directly in the terminal window (this one is cool)
calc fact 10
Calculate the factorial of 10 (this is just one of many math calculations you can perform directly in the terminal)
cat /proc/cpuinfo
Display cpu info
cat /proc/meminfo
Display memory usage
cat /proc/net/dev
Display networking devices
cat /proc/uptime
Display performance information
cat /proc/version
Display kernel version
cat <filename>
Display file contents
cd -
Toggle between current directory and last directory
cd ..
Move to parent (higher level) directory. Note the space!
cd ~
Go to home directory
cd $HOME
Go to home directory
cd
Go to home directory (when used alone)
cdrecord -scanbus
List SCSI (small computer system interface) devices. This answers the question: What kind of optical drive do I have?
chmod 755 <filename>
Set permissions to 755. Corresponds to these permissions: (-rwx-r-x-r-x), arranged in this sequence: (owner-group-other), where the numeric values are: (read=4, write=2, execute=1). You need elevated permissions to run this (sudo).
chmod a+x <filename>
Add execute permission to all users. You need elevated permissions to run this (sudo).
chown <username>
changes ownership of a file or directory to <username>. Check it with ls -l. You need elevated permissions to run this (sudo).
cp <file> <file>.backup
Make a backup copy of a file (named file.backup)
cp <file1> <file2>
Copy file1, use it to create file2
cp -r <directory1> <directory2>/
Copy directory1 and all its contents (recursively) into directory2
date
Display date
dd if=/dev/zero of=/dev/sdb
Zero the sdb drive. You may want to use GParted to format the drive afterward. You need elevated permissions to run this (sudo).
df -Th
Display disk space usage
dmesg>dmesg.txt
Take detailed messages from OS and input to text file
dmidecode
Display a LOT of system information. I usually pipe output to less. You need elevated permissions to run this (sudo).
dmidecode -t 0
Display BIOS information. You need elevated permissions to run this (sudo).
dmidecode -t 4
Display CPU information. You need elevated permissions to run this (sudo).
dpkg –get-selections | grep apache
Search for installed packages related to Apache
dpkg -L <package_name>
Shows you where in the filesystem the package components were installed
du / -bh | less
Display detailed disk use for each subdirectory
echo $PATH
Print the environment variable PATH
echo -e
Display a line of text and enable interpretation of backslash escapes. This is most helpful when redirecting the output into a file as in: echo -e ‘Hello\nWorld!’ | tee -a test.txt (see my description of tee -a below)
env
Display environment variables like USER, LANG, SHELL, PATH, TERM, etc.
eog <picture_name>
Opens a picture with the Eye of Gnome Image Viewer
exit
Quit the terminal (or give up super-powers if you’ve previously done sudo su)
fdisk -l
List partition tables
file <package_name>
Show the properties/compression of a file or package
find / -name <filename>
Find the file. Although slower than locate, find is more flexible and does not rely on a cache that may be outdated. If you don’t specify a directory, it defaults to the current directory and searches recursively (also looks in subdirectories). If you are looking through directories that require superuser for read permission, you’ll get Permission denied for every single file in those directories, so run as root (sudo) if you’re searching those directories. (More Info)
find . -name “*.java” | xargs grep “main”
Search for all java files in the current directory and all subdirectories, then search those files for the string main. xargs is used to pass a list of files as an argument. Without it, grep will only search through filenames themselves for the string main.
find dir -name ‘*.jpg’ -type f -print0 | xargs -0 -r ls -l
Find every file with the extension .jpg in the directory dir and all sub-directories and use -print0 to print full file names. -print0 is used with the -0 option of xargs to process file names with white space correctly. xargs is used to execute a command followed by items read from standard input. The -r option prevents xargs from executing the command if there is no input. Basically, use this to run a command and send it a bunch of files with the same extension from a specific parent directory. You could similarly use something like this: ls -l `find dir -type f -name \*.jpg`, or this: ls -l $(find dir -type f -name \*.jpg), but neither of those deal well with whitespace in filenames.
free
Display memory usage
gnome-system-log
Easy way to view all the system logs.
grep <string> <filename>
Search through file(s) and display lines containing matching string
grep btime /proc/stat | grep -Eo “[[:digit:]]+”
Get the number of seconds since the OS was started
gzip
Compress or expand files and directories
history | less
Display the last 1000 commands
hostname
Display the name of the local host
hwclock –show
Display time. You need elevated permissions to run this (sudo).
id
Display user id (uid) and group id (gid)
ifconfig
Display your local IP address and netmask
iwconfig
Wireless network interface
iwlist
Display wireless network information
killall process
Kill process by name. You need elevated permissions to run this (sudo).
last -x | grep shutdown | head -1 | grep -Eo “[A-Z][a-z]{2} [[:digit:] ][[:digit:]] [[:digit:]]{2}:[[:digit:]]{2}”
Get the date and time of the last system shutdown
less <filename>
Pager utility that allows scrolling while reading contents of file. While you’re using less, type h to see the help menu. As it will tell you, you can search for a word like greeen by typing /greeen, then find the next match by pressing n. You can start the search anew by going back to the top of the file by pressing g. To exit less, just type q.
locate <filename>
Searches for file using an indexed database (updated daily at 4:20 by default), so that it is much faster than find. Update the database manually with updatedb
logout
Quit shell session (only for a shell you’ve logged into like one of the virtual consoles)
ls
List non-hidden files and subfolders in current directory (like dir for windows). Use -R for recursive and -a to include hidden files.
ls -l <filename>
Display file access permissions for all files in the current directory. The format for permissions is drwxrwxrwx where the order is owner-group-other and the numeric values are read=4, write=2, execute=1.
ls /usr/bin | less
List all available applications, in case you’ve forgotten how to open Open Office Writer or another application from the terminal (oowriter)
lsb_release -a
Display which version of Ubuntu you’re using
lshw -C network
Display more networking information
lsmod
Display kernel modules currently loaded
lspci -nv | less
Display sound, video, and networking hardware
lsusb
Display usb-connected hardware
man <command>
Read the command’s man page (manual)
mkdir <dirname>
Create new directory at specified location
modprobe -r <modulename>
Remove the kernel module. You need elevated permissions to run this (sudo).
modprobe -t net
Cycle through network drivers, tries to load each one until it finds one that works. You need elevated permissions to run this (sudo).
mv <file> <dir>
Move file to specified directory
mv <file1> <file2>
Rename file1 to file2
netstat -rn
Display routing table
printenv
Print environmental variables
ps -Af
List the processes currently running by this user. There are many useful options, view them with ps –help
pwd
Print working directory (“Tell me where I am!”)
rm <filename>
Delete file
rm -rf <dir>
Delete directory and all it’s contents
rm *.txt
Removes all files that end in txt in current directory
rmdir <dir>
Delete directory (will only work if it’s empty)
route
Display your default gateway listed under “default”
shred -zuv -n 7 <file>
Completely destroy all traces of the file. This takes a while. -n 7 means seven overwrites, -z means zero the bits afterward to hide shredding, -u means delete the file when done, and -v means verbose. You need elevated permissions to run this (sudo).
shutdown -h now
Shutdown now. You need elevated permissions to run this (sudo).
shutdown -r now
Restart now. You need elevated permissions to run this (sudo).
ssh <IP address>
Log into remote computer
sudo -i
Open the root shell, giving yourself superuser permissions until you relegate your powers with exit. Unlike sudo su which does the same thing, this method of starting the root shell is uncorrupted by a user’s environmental variables.
sudo su
Open the root shell, like sudo -i, but this method retains the user’s environmental variables. Relegate superuser permissions and return to normal shell with exit.
tar czf <dirname>.tgz <dirname>
Creates a compressed archive of the specified directory and all files/directories under it.
tar zxvf <archive>
Expand the contents of a compressed archive and extract to current directory. The -z is for gzip (use it when the archive ends with .tar.gz) and -j is for bzip2 (use it when the archive ends with .tar.bz2), the -x is for extracting files from an archive, the -v is for verbose, and the -f means use the archive file.
tee
Duplicates standard input. Said another way, it reads from standard input and writes to standard output and files. I think of it as a fancy > (redirect operator), because it does the exact same thing as > without preventing the stdout from displaying on the console. Example: echo ‘Hello World!’ | tee test.txt
tee -a
Duplicates standard input as explained above, except the -a means to open the resulting file in append mode, so that any existing file by that name is not overwritten and the text is just added to the end. tee is similar to > and tee -a is similar to >>.
top
List current processes by cpu use. This is very useful. Press q to quit and h for help.
touch <filename>
Create an empty file if it doesn’t exist
tty
Display the name of the current terminal
uname -a
Display your linux kernel
uname -m
Display your machine’s processor architecture
updatedb
Update the database used by the locate command to find files quickly. You need elevated permissions to run this (sudo).
whatis <command>
Returns one-line synopsis from the command’s man page
whereis <command>
Returns the location of the program in the filesystem
which <command>
Returns the application’s path
who
Display the users logged into the machine
whoami
Display your login name
sfill -fvll /
Overwrite all empty space on your hard drive. sfill is available from the secure-delete package and is not installed by default. The -f is for fast, which makes this overwrite less secure, the -v is for verbose, and the -ll is for less and lesser, which makes this overwrite less and less secure (I think it only ends up doing one overwrite). Obviously, this method is not secure, but I am not patient enough to wait the requisite amount of time for a secure overwrite (it takes days to weeks for large amounts of data). You need elevated permissions to run this (sudo).
tail –follow test.log
This will display the output of test.log as it is being written to by another program

BASH Resources

LinuxCommand.org
Excellent BASH walkthrough
Linux Commands – A Practical Reference
List of more BASH command examples
The Official BASH Manual
Use this when you’re scripting or trying complex commands
UbuntuGuide.org
Easy to follow Ubuntu wiki
Official Ubuntu Documentation
The official documentation is also pretty good

About GreeenGuru

Computer Enthusiast
This entry was posted in Ubuntu and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>