Linux Shortcuts and Tricks

Linux Shortcuts and Tricks

Linux Shortcuts and Tricks

The Linux command line offers a much easier, and cross-distribution, method of completing common tasks. Certain commands and syntaxes may be cumbersome to memorize, there are several helpful command line tips and cool tricks to make your work in the terminal much easier. They’ll definitely get you more productive than before and make you enjoy using the terminal. Here are a few tricks and shortcuts that will save you a lot of time while working with Linux command line.
Todays, I’ll show you some pro Linux command tricks that will save yours a lot of time.

  1. Switch back to the last working directory:

Suppose you end up in a long directory path and then you move to another directory in a totally different path. And then you realize that you have to go back to the previous directory you were in. In this case, all you need to do is to type this command:

cd -

This will put you back in the last working directory. You don’t need to type the long directory path or copy paste it anymore.

2. Go back to home directory

This is way too obvious. You can use the command below to move to your home directory from anywhere in Linux command-line:

cd ~

However, you can also use just cd to go back to home directory:

cd

Most modern Linux distributions have the shell pre-configured for this command. Saves you at least two keystrokes here.

3. List the contents of a directory

You must be guessing what’s the trick in the command for listing the contents of a directory. Everyone knows to use the ls -l for this purpose.
And that’s the thing. Most people use ls -l to list the contents of the directory, whereas the same can be done with the following command:

ll

Again, this depends on the Linux distributions and shell configuration, but chances are that you’ll be able to use it in most Linux distributions.

4. Running multiple commands in one single command

Suppose, you have to run several commands one after another. Do you wait for the first command to finish running and then execute the next one? You can use the ‘;’ separator for this purpose. This way, you can run a number of commands in one line. No need to wait for the previous commands to finish their business.

command_1; command_2; command_3

5. Running multiple commands in one single command only if the previous command was successful

In the previous command, you saw how to run several commands in one single command to save time. But what if you have to make sure that commands don’t fail?

You can use && separator for this case. && makes sure that the next command will only run when the previous command was successful.

command_1 && command_2

A good example of this command is when you use sudo apt update && sudo apt upgrade to upgrade your system.

6. Easily search and use the commands that you had used in the past

Imagine a situation where you used a long command couple of minutes/hours ago and you have to use it again. Problem is that you cannot remember the exact command anymore.

Reverse search is your savior here. You can search for the command in the history using a search term.

Just use the keys ctrl+r to initiate reverse search and type some part of the command. It will look up into the history and will show you the commands that matches the search term.

ctrl+r search_term

By default, it will show just one result. To see more results matching your search term, you will have to use ctrl+r again and again. To quit reverse search, just use Ctrl+C.

ubuntu1

Note that in some Bash shells, you can also use Page Up and Down key with your search term and it will autocomplete the command.

7. Unfreeze your Linux terminal from accidental Ctrl+S

You probably are habitual of using Ctrl+S for saving. But if you use that in Linux terminal, you’ll have a frozen terminal.
Don’t worry, you don’t have to close the terminal, not anymore. Just use Ctrl+Q and you can use the terminal again.

ctrl+Q

8. Move to beginning or end of line

Suppose you are typing a long command and midway you realize that you had to change something at the beginning. You would use several left arrow keystrokes to move to the start of the line. And similarly for going to the end of the line.
You can use Home and End keys here of course but alternatively, you can use Ctrl+A to go to the beginning of the line and Ctrl+E to go to the end.

9. Reading a log file in real time

In situations where you need to analyze the logs while the application is running, you can use the tail command with -f option.

tail -f path_to_Log

You can also use the regular grep options to display only those lines that are meaningful to you:

tail -f path_to_log | grep search_term

You can also use the option F here. This will keep the tail running even if the log file is deleted. So if the log file is created again, tail will continue logging.

10. Reading compressed logs without extracting

Server logs are usually gzip compressed to save disk space. It creates an issue for the developer or sysadmin analyzing the logs. You might have to scp it to your local and then extract it to access the files because, at times, you don’t have write permission to extract the logs.
Thankfully, z commands save you in such situations. z commands provide alternatives of the regular commands that you use to deal with log files such as less, cat, grep etc.
So you get zless, zcat, zgrep etc and you don’t even have to explicitly extract the compressed files. Please refer to my earlier article about using z commands to real compressed logs in detail.

This was one of the secret finds that won me a coffee from my colleague.

11. Use less to read files

To see the contents of a file, cat is not the best option especially if it is a big file. cat command will display the entire file on your screen.

You can use Vi, Vim or other terminal based text editors but if you just want to read a file, less command is a far better choice.

less path_to_file

You can search for terms inside less, move by page, display with line numbers etc.
Using the argument of the previous command comes handy in many situations.

Say you have to create a directory and then go into the newly created directory. There you can use the !$ options.

12. Using alias to fix typos

You probably already know what is an alias command in Linux. What you can do is, to use them to fix typos.
For example, you might often mistype grep as gerp. If you put an alias in your bashrc in this fashion:

alias gerp=grep

This way you won’t have to retype the command again.

13. Copy Paste in Linux terminal

This one is slightly ambiguous because it depends on Linux distributions and terminal applications. But in general, you should be able to copy paste commands with these shortcuts:

  • Select the text for copying and right click for paste (works in Putty and other Windows SSH clients)
  • Select the text for copying and middle click (scroll button on the mouse) for paste
  • Ctrl+Shift+C for copy and Ctrl+Shift+V for paste

14. Kill a running command/process

This one is perhaps way too obvious. If there is a command running in the foreground and you want to exit it, you can press Ctrl+C to stop that running command.

15. Run your program after session killing

When you run any program in the background and close your shell, definitely it will be killed, what about if it continues running after closing the shell.

This can be done using the nohup command, which stands for no hangup.

nohup wget site.com/file.zip

This command is one of the most useful Linux command line tricks for most webmasters.
A file will be generated in the same directory with the name nohup.out contains the output of the running program.

16. Using yes command for commands or scripts that need interactive response

If there are some commands or scripts that need user interaction and you know that you have to enter Y each time it requires an input, you can use Yes command.
Just use it in the below fashion:

yes | command_or_script

17. Empty a file without deleting it

If you just want to empty the contents of a text file without deleting the file itself, you can use a command similar to this:

> filename

18. Find if there are files containing a particular text

There are multiple ways to search and find in Linux command line. But in the case when you just want to see if there are files that contain a particular text, you can use this command:

grep -Pri Search_Term path_to_directory

I highly advise mastering find command though.

19. Using help with any command

I’ll conclude this article with one more obvious and yet very important ‘trick’, using help with a command or a command line tool.
Almost all command and command line tool come with a help page that shows how to use the command. Often using help will tell you the basic usage of the tool/command.

Just use it in this fashion:

command_tool --help

20. Count number of files within a directory in Linux (not using wc)

ls -l . | egrep -c ‘^-’

21. Take top n files in a folder/directory and then next m files into a new directory

ls dir1 | head -n 10 | xargs -I X cp dir1/X dir2
ls dir1 |tail -n +11 | head -n 5 | xargs -I X cp dir1/X dir2

22. Move files from one location to another

mv -v ~/dir1/* ~/dir2/

23. Move a random shuffled sample subset of files to another location

shuf -zen200 source/* | xargs -0 mv -t dest

24. Save files list to a text file

ls > filenames.txt

25. Find specific files based on filenames list and move them

xargs -a file_list.txt mv -t /path/to/dest

26. Find files common to two directories

comm -12 <(ls dir1) <(ls dir2)

The output will be differentiated by 0, 1, or 2 leading tabs as:

files only in dir1
files only in dir2
files in both dirs

27. Using Screen

screen -S <any name>      # To create a screen
screen -ls                # To see a list of the ones you created
screen -d -r <name of a detached screen> # To restore detached
screen -X -S [session # you want to kill] quit  # To kill a screen

28. Finding the biggest files

ls -lSrh
ls -lSrh *.<file format extension like txt or mp3>

29. Look for the largest directories

du -kx | egrep -v "\./.+/" | sort -n

30. man page descriptions for a particular keyword

man -k <insert keyword>   # use / and search for a term by typing it

31. Listing today’s files only

ls -al --time-style=+%D | grep `date +%D`

32. Merging columns in files

#!/bin/sh
length=`wc -l $1 | awk '{print $1}'`
count=1
[ -f $3 ] && echo "Optionally removing $3" && rm -i $3
while [ "$count" -le "$length" ] ; do
      a=`head -$count $1 | tail -1`
      b=`head -$count $2 | tail -1`
      echo "$a      $b" >> $3
      count=`expr $count + 1`
done

chmod u+x merge.sh # to make the file executable

/path/to/merge.sh file1 file2 file3

33. Find and execute

find . -name '*.gz'  # locate all the gzip archives in the pwd
find . -name '*.gz' | xargs gunzip -vt

34. Rename and resize images

#!/bin/sh
counter=1
root=mypict
resolution=400x300
for i in `ls -1 $1/*.jpg`; do
        echo "Now working on $i"
        convert -resize $resolution $i ${root}_${counter}.jpg
        counter=`expr $counter + 1`
done

chmod u+x picturename.sh # to make it executable

picturename.sh /path/to/pictdir

35. htop

Once htop is installed, you can run it by typing htop on the command line. When you do, you’ll get a full overview of all the processes running on your system along with details like process IDs, CPU and RAM usage, and how long they’ve been running.

36. ranger

Once installed, type ranger in the command line and your terminal will transform into an interface that makes it easy to navigate your entire filesystem using just a keyboard (though you can use your mouse too, if you want).

37. tmux

To split screens either vertically or horizontally

Ctrl+B and then Shift + 5        # Vertical split
Ctrl+B and then Shift + "        # Horizontal split
Ctrl+B and then direction keys   # To navigate screens
Ctrl+B and then X                # To kill
Ctrl+B and then [                # To get scroll mode, hit q to exit

38. Apropos

apropos <keyword>

This will match the “keyword” string with said command’s help string and display a list of such commands

39. Transferring files without ftp or scp

# Run on destination server

nc -l -p 1234 | uncompress -c | tar xvfp -  # Run on sending server
tar cfp - /some/dir | compress -c | nc -w 3 [destination] 1234

40. Create Aliases for SSH logins

vim ~/.bash_aliasesType your list of aliases in the format
│alias <name>='ssh user@hostaddress'source ~/.bash_aliases

# If you get a Bad owner or permissions on /Users/username/.ssh/config error, then type

chmod 600 ~/.ssh/config

now just type ssh <alias-name>

41. SSH login without password

ssh-keygen
ssh-copy-id -i root@ip_address  # enter login password when prompted

Then just type ssh root@ip_address and you’ll be logged in automatically

42. cmatrix

Once cmatrix is installed, you can run it by typing cmatrix on the command line. When you do, you’ll get a screen like this. It’s just a cool effect. You can use this as a screensaver for your terminal when you leave it idle.

43. Command history

export HISTTIMEFORMAT="%d/%m/%y %T "    # Add this to ~/.bashrc
source ~/.bashrchistory

44. Check the top n files that are eating out your space

du -hsx * | sort -rh | head -<insert number n>
du -hsx * | sort -rh | head -11

45. Get Statistics related to a file

stat filename.extension

46. Learn a random Linux command

man $(ls /bin | shuf | head -1)

47. Conditional Execution

To run two commands, one after successfully completing the other, put both commands on the same line, separated by a &&, or double ampersand

You can use the sleep command with does a countdown from the number of seconds given to complete ,as a time delay for a second command

sleep 100 && <insert second command>

48. Dealing with jobs and processes

Let’s assume you have a process that takes time to complete and doesn’t allow you to do anything else in the terminal. You can hit Ctrl+z and temporarily suspend it.

bg          # This will make the suspended process run in background
fg          # To bring it back to the foreground
jobs        # This will give a list of processes with an integer id
fg %<number>  # if you want to foreground an older process
bg %<number>  # if you want an older process in the background

49. Repeat previous argument

!$ or "Esc + ."

50. Run Commands At a Specific Time

With the at command, you can specify a date and time. Doing so will open up an input prompt where you can enter a sequence of commands to be run at the date and time you gave. When you’re done, type Ctrl + D to quit the input prompt.

at 10:30 PM 15/07/20

If you this error when attempting to set new at jobs:

Can’t open /var/run/atd.pid to signal atd. No atd running?

sudo service atd start

51. xargs

xargs is an essential tool which enhances functionality of front line commands like find, grep or cut and gives more power to your shell script

This command can be used with any command which generates a long list of inputs. It was initially use to avoid “Argument list too long” errors and by using xargs you send sub-list to any command which is shorter than “ARG_MAX” and that’s how xargs avoid “Argument list too long” error

  • It doesn’t handle files which has newlines or white space in its name and to avoid this problem one should always use “xargs -0”. xargs -0(Zero) changes separator to null character so its important that input feed to xargs is also use null as separator.
  • The default command executed by xargs is /bin/echo and it will simply display file names.
  • By default end of file string is “_” and if this string occurs in input the rest of input is ignored by xargs. Though you can change end of file string by using option “-eof”.
  • We can force xargs to use at most max-args arguments per command line with -n <number> after xargs
<previous command> | xargs -0 -I X <another command> X

52. Downloading youtube playlist using youtube-dl

pip install -upgrade youtube-dl

youtube-dl -i --yes-playlist --playlist-start 1 --write-thumbnail --write-auto-sub --sub-format srt --format mp4 -o "%(playlist_index)s-%(title)s.%(ext)s" <insert playlist link>

53. Split Folder with many files into small sub folders in order

Let’s say your you have a directory with 101,834 files and you want them in smaller sets of 20,000 each so that you don’t run into memory errors when you use the data for some algorithm.

You can use the following to batch it and run on small subsets

In this example the main directory is called dir and the batches are going to be named subdir1, subdir2,…,subdir5.

ls dir|head -n 20000 | xargs -I X cp dir/X subdir1
ls dir|tail -n +20001 | head -n 20000 | xargs -I X cp dir/X subdir2
ls dir|tail -n +40001 | head -n 20000 | xargs -I X cp dir/X subdir3
ls dir|tail -n +60001 | head -n 20000 | xargs -I X cp dir/X subdir4
ls dir|tail -n +80001 | head -n 20834 | xargs -I X cp dir/X subdir5

54. Untar a file

tar xvzf file.tar.gz

x: This tells tar to extract the files.

v: This option will list all of the files one by one in the archive. The “v” stands for “verbose.”

z: The z option is very important and tells the tar command to uncompress the file (gzip).

f: This options tells tar that you are going to give it a file name to work with.

sudo apt-get install dtrx
dtrx file.tar.gz
dtrx file.tar.bz2

55. Check your architecture

Using the following command, you can get your PC architecture.

getconf  LONG_BIT

56. Answer bot using yes & no commands

It’s like an answer bot for those commands which require the user to say yes.

Y using the yes command:

yes | apt-get update

Or maybe you want to automate saying no; this can be done using the following command:

yes no | command

57. Create a file with a specific size

Use the dd command to create a file with a specific size:

dd if=/dev/zero of=out.txt bs=1M count=10

This will create a file with a 10-megabyte size filled with zeros.

58. Run the last command as root

Sometimes you forget to type sudo before your command that requires root privileges to run, you don’t have to rewrite it, just type:

sudo !!

59. Record your command-line session

If you want to record what you’ve typed in your shell screen, you can use the script command, which will save all of your typing to a file named typescript.

script

Once you type exit, all of your commands will be written to that file so you can review them later.

60. Replacing spaces with tabs

You can replace any character with any other character using the tr command, which is very handy.

cat education.txt | tr ':[space]:' '\t' > out.txt

This command will replace the spaces with tabs.

61. Convert character case

cat my_file | tr a-z A-Z > output.txt

This command converts the content of the file to upper case using the tr command.

62. Powerful xargs command

We can say that xargs command is one of the most essential Linux command line tricks, you can use this command to pass outputs between commands as arguments, for example, you may search for png files and compress them or do anything with them.

find . -name "*.png" -type f -print | xargs tar -cvzf pics.tar.gz

Or maybe you have a list of URLs in a file, and you want to download them or process them differently:

cat links.txt | xargs wget

The cat command result is passed to the end of the xargs command.

What if your command needs the output in the middle?
Just use {} combined with –i parameter to replace the arguments in the place where the result should go like this:

ls /etc/*.conf | xargs -i cp {} /home/edunews/Desktop/out

63. Keep executing a command until it succeeds

To keep executing a command until it finally succeeds, use the exit code of the command directly: while ! [command]; do sleep 1; done

$ while ! ./run.sh; do sleep 1; done 
cat: run.sh: No such file or directory 
cat: run.sh: No such file or directory 
linoxide.com

The command kept running until it found run.sh and printed out its content.

64. View progress of file transfers

In Linux, you cannot really know the rate of a file transfer progress until it’s done. Using the pv command, you can monitor the progress of file transfers.

$ pv access.log | gzip > access.log.gz 
611MB 0:00:11 [58.3MB/s] [=> ] 15% ETA 0:00:59

65. Easily schedule events

Using the at command, you can easily schedule events at anytime.

echo wget https://sample.site/test.mp4 | at 2:00 PM

To view the queued jobs, type atq.

66. Compress, split and encrypt  files

Trying to transfer large files across computers is a tedious task. We can easily do this by compressing the files and creating a multi-part archive if the files are extremely large. To encrypt, we add the -e switch.

$ zip -re test.zip AdbeRdr11010_en_US.exe run.sh Smart_Switch_pc_setup.exe 
Enter password: 
Verify password: 
adding: AdbeRdr11010_en_US.exe (deflated 0%) 
adding: run.sh (stored 0%) 
adding: Smart_Switch_pc_setup.exe (deflated 2%)

67. Stress test your battery

Do you want to check how long your battery can last under 100% CPU usage? Try this command:

$ cat /dev/urandom > /dev/null

68. Renaming/moving files with suffixes

If you want to quickly rename or move a bunch of files with suffix, try this command.

$ cp /home/sample.txt{,-old}

This will translate to:

$ cp /home/sample.txt /home/sample.txt-old

To rename files of a particular extension in batch, try this:

$ ls
text_comes_here_1.txt
text_comes_here_2.txt
text_comes_here_3.txt
text_comes_here_4.txt 

$ rename 's/comes_here_/goes_there/' *.txt
$ls
text_goes_there_1.txt
text_goes_there_2.txt
text_goes_there_3.txt

69. Replacement for id command

You can use awk in /proc/self/status to filter same results that id command gives

foo@localhost:/root$ awk -F: 'END {print "uid:"u" gid:"g" groups:"gg}{if($1=="Uid"){split($2,a," ");u=a[1]}if($1=="Gid"){split($2,a," ");g=a[1]}if($1=="Groups"){gg=$2}}' /proc/self/statusuid:1000 gid:1000 groups:       1000

70. Lock or Hide a File or Directory in Linux

The simplest way of locking a file or directory is by using Linux file permissions. In case your the owner of a file or directory, you can block (remove read, write and execute privileges) other users and groups from accessing it as follows:

To hide the file/directory from other system users, rename it with a (.) at the start of the file or directory:

71. Translate rwx Permissions into Octal Format in Linux

By default, when you run the ls command, it displays file permissions in rwx format, but to understand the equivalence of this format and the octal format, you can learn how to translate rwx permissions into Octal format in Linux.

72. How to Use ‘su’ When ‘sudo’ Fails

Although sudo command is used to execute commands with superuser privileges, there are moments when it fails to work as in the example below.

Here, I want to empty the contents of a large file named uptime.log but the operation has failed even when I used sudo.

In such as case, you need to switch to the root user account using su command to perform the operation like so:

73. Delete File Permanently in Linux

Normally, we use the rm command to delete files from a Linux system, however, these files do not completely get deleted, they are simply stored and hidden on the hard disk and can still be recovered these files in Linux and viewed by another person.

To prevent this, we can use the shred command which overwrites the file content and optionally deletes the file as well.

The options used in the above command:

  1. -z– adds a final overwrite with zeros to hide shredding.
  2. -u– helps to truncate and remove file after overwriting.
  3. -v– shows progress.

Read through shred man page for additional usage instructions:

74. Check for Spelling of Words in Linux

The look command displays lines beginning with a given string, it can help you to check for the spelling of word from within the command line. Although it is not so effective and reliable, look is still a useful alternative to other powerful spelling-checkers:

75. Search for Description of Keyword in Manual Page

The man command is used to display manual entry pages of commands, when used with the -k switch, it searches the short descriptions and manual page names for the keyword printf (such as adjust, apache and php in the commands below) as regular expression.

76. Watch Logs in Real-Time in Linux

With watch command, you can run another Linux command periodically while displaying its output on fullscreen and alongside tail command which is used to view the last parts of a file, it is possible to watch the recording of log entries in a logfile.

In the example below, you will watch the system authentication logfile. Open two terminal windows, display the log file for watching in real-time in the first window like so:

You can also use tail command which shows the last parts of a file. Its -f flag enables watching changes in a file in real-time, therefore it is possible to watch the recording of log entries in a log file.

And run the commands below in the second terminal as you observe the logfile content from the first window:

77. Find the right command

Executing the right command can be vital for your system. However in Linux there are so many different command lines that they are often hard to remember. So how do you search for the right command you need? The answer is apropos. All you need to run is:

# apropos <description>

Where you should change the “description” with the actual description of the command you are looking for. Here is a good example:

# apropos "list directory" 
dir (1) - list directory contents
ls (1) - list directory contentsnt
fsls (8) - list directory contents on an NTFS filesystem
vdir (1) - list directory contents

78. Use midnight Commander

If you are not used to using commands such cdcpmvrm than you can use the midnight command. It is an easy to use visual shell in which you can also use mouse:

F1 – F12 keys, you can easy perform different tasks. Simply check the legend at the bottom. To select a file or folder click the “Insert” button.

In short the midnight command is called “mc“. To install mc on your system simply run:

$ sudo apt-get install mc        [On Debian based systems]

# yum install mc                 [On Fedora based systems]

Here is a simple example of using midnight commander. Open mc by simply typing:

# mc

Now use the TAB button to switch between windows – left and right. I have a LibreOffice file that I will move to “Software” folder:

To move the file in the new directory press F6 button on your keyboard. MC will now ask you for confirmation:

Once confirmed, the file will be moved in the new destination directory.

79. Shutdown Computer at Specific Time

Sometimes you will need to shutdown your computer some hours after your work hours have ended. You can configure your computer to shut down at specific time by using:

$ sudo shutdown 21:00

This will tell your computer to shut down at the specific time you have provided. You can also tell the system to shutdown after specific amount of minutes:

$ sudo shutdown +15

That way the system will shut down in 15 minutes.

80. Show Information about Known Users

You can use a simple command to list your Linux system users and some basic information about them. Simply use:

# lslogins

81. Build Directory Trees with one Command

You probably know that you can create new directories by using the mkdir command. So if you want to create a new folder you will run something like this:

# mkdir new_folder

But what, if you want to create 5 subfolders within that folder? Running mkdir 5 times in a row is not a good solution. Instead you can use -p option like that:

# mkdir -p new_folder/{folder_1,folder_2,folder_3,folder_4,folder_5}

In the end you should have 5 folders located in new_folder:

# ls new_folder/ 
folder_1 folder_2 folder_3 folder_4 folder_5

82. Deleting Larger Files

Sometimes files can grow extremely large. I have seen cases where a single log file went over 250 GB large due to poor administrating skills. Removing the file with rm utility might not be sufficient in such cases due to the fact that there is extremely large amount of data that needs to be removed. The operation will be a “heavy” one and should be avoided. Instead, you can go with a really simple solution:

# > /path-to-file/huge_file.log

Where of course you will need to change the path and the file names with the exact ones to match your case. The above command will simply write an empty output to the file. In more simpler words it will empty the file without causing high I/O on your system.

Useful Command Line Keyboard Shortcuts

The following keyboard shortcuts are useful and will save you time:

  • CTRL+U: Cuts text up until the cursor.
  • CTRL+K: Cuts text from the cursor until the end of the line.
  • CTRL+Y: Pastes text.
  • CTRL+E: Moves the cursor to the end of the line.
  • CTRL+A: Moves the cursor to the beginning of the line.
  • ALT+F: Jumps forward to the next space.
  • ALT+B: Skips back to the previous space.
  • ALT+Backspace: Deletes the previous word.
  • CTRL+W: Cuts the word behind the cursor.
  • Shift+Insert: Pastes text into a terminal.

So that the commands above make sense, look at the next line of text.

sudo apt-get intall programname

There’s a spelling error in the command, and for the command to work, intall needs to be changed to install.

Imagine the cursor is at the end of the line. There are several ways to get back to the word install to change it.
You could press ALT+B twice, which would put the cursor in the following position (denoted by the ^ symbol):

sudo apt-get^install programname

Then, press the cursor key and insert the s into install.

Another useful command is Shift+Insert, especially if you need to copy text from a browser into the terminal.

Shorcut Description
Long press on Super (Windows key) Opens up help for the most common keyboard shortcuts
Alt+Left Mouse Click Allows to moves the current window

Using the console

To open a console open the ‘Dash’ and type in ‘Terminal’. Alternatively you can use the shortcut Ctrl+Alt+T.

This opens a console window which allows you to issue commands.

Using the vim command line editor

Ubuntu offers several editors which are installed by default. The most common command line editor is vim.

To install vim on your Ubuntu machine use the following command.

sudo apt-get install vim

Start vim from the command line. vim has two modes, one editing mode and other mode in which you can move within the file.

Here is a minimal command reference for vim:

  • i– Enter interactive mode to edit the file
  • Escape– Leave interactive mode
  • /– Search in file
  • :wq– Saves the file and exists vim
  • :q!– Exists vim without saving

Find files

The following demonstrates the usage of the find command.

Command Description
find dir -name “pattern” 2>/dev/null Finds all files which recursively apply to the pattern “pattern” starting from the directory “dir”. The 2> sends all error messages to the null device.
find . -name ‘*.java’ -newer build.xml -print Search for all java files newer than the file build.xml
find . -name ‘*.java’ -mtime +7 -print Search for all java files newer than 7 dates
find . -name ‘*.java’ -mtime +7 -print0 xargs -0 grep ‘swt’

The find command can also be combined with the grep command

Change owner of files and directories

Command Description
chown -R www-data:www-data mydir Change recursively the owner and the group of the directory “mydir” and its subdirectories.

Creating links

You can create a soft link to a file or directory using the following command.

# Create a new soft link via

# ln -s target link

# For example

ln -s ~/workspace/e4-dev e4tools

Environment Variables

Command Description
echo $VARIABLE Prints the content of the environment variable
sudo /etc/init.d/tomcat5 start/stop Starts / stops the tomcat server
sudo -i Switches to root

Important files

File Description
/etc/issue Contains the Ubuntu version you are running
lsb_release -a Prints out the Ubuntu version you are running
/etc/apt/sources.list Contains the available sources for software installation
/usr/share/tomcat Installation directory for tomcat
/var/www/vhosts/domain1 Contains on my v-server the user directory for a specific domain which is hosted on this server

Package management

On the command line Ubuntu allows to install / remove and search for packages via the following commands.

Command Description
sudo apt-get install paketname Installs a package
apt-cache search openjdk Search for all packages which contain openjdk. The found package can get installed via the “apt-get install” command.
apt-cache show eclipse Write down the meta-data of a package, e.g., the package description and the package maintainer
sudo apt-get remove package Removes a package but leave the configuration data active
sudo apt-get purge package Removes a package and orphaned dependencies and its configuration files
sudo apt-get update Update the local package list
sudo apt-get upgrade Updates any installed packages for which an update is available. Will not install new packages or remove packages to satisfy dependencies.
sudo apt-get dist-upgrade Install available updates for the Ubuntu release you already have installed. Also installs new packages or removes existing packages to satisfy dependencies.
dpkg -L packagename Lists all files and their location in a package
sudo updatedb; locate javac Updates the installation database and locates the javac command.

To search for the installed packages use the following command.

 cat /var/log/dpkg.log | grep "\ install\ "

I hope this post helps you to understand all the “Linux Shortcuts and Tricks”. Any that you use in Linux and i forget in this post please do comment in the below comment section.

Keep learning 🙂

Leave a Reply

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