Friday, November 6, 2015

Linux 14 Command Line Tips & Tricks

                               

In this article you will find a list of 14 practical Linux command-line tips and tricks – in handy Q&A form – that are aimed to provide valuable information for Linux beginners.
I am new to Linux. Experts Q1: advise to never log in as root. How can I find out whether I have logged in as root or not?
As you are new to Linux, the first thing that you should know is what root means and why experts say that you should never log in as root (until and unless it is absolutely required).
Root is the username for a Linux user account that has read-write-delete access to virtually anything and everything on the system. This user exists by default on every Linux distribution, though some of them (like Ubuntu) require it to be activated manually before first use. Activating here means configuring the password for root using the ‘passwd’ command. The root user is also known as superuser.
Since the root user account has unlimited privileges, you can do almost anything on a Linux system while logged in as root. For example, you can delete a standard Linux command/binary, change a system configuration file, change user passwords, alter network settings, change firewall configuration and so on. The list is endless. But, as they say, with great power comes great responsibility. Unfortunately, normal users are usually not responsible and careful enough to use the root account. Think of a scenario where a normal user – logged-in as root – accidentally changes some firewall settings of the system; or worse, accidentally executes ‘rm -rf *’ from the root directory (/).
You just cannot imagine the extent of damage that can be caused once a root account is accidentally misused, or compromised by a hacker. This is the reason why it is always advised to stay away from the root account until and unless it is absolutely necessary. Even when it is required to do some stuff that requires root privileges, instead of logging in as root, always use commands like ‘sudo’ or ‘su -c’ to gain root privileges, as these make sure that the privileges are acquired for a single command execution or for a certain period of time (at the maximum).
Sometimes when I start a program Q2: from the command line, the prompt gets blocked until I close the program. How do I stop this?
Whenever you run a command in Linux, the command prompt does not get freed up until the command completes. A command may complete in a few seconds or even take minutes, depending upon what it is up to. For example, if you are trying to find a file in a complete system using the ‘find’ command, then it may consume more time than when trying to find a file in a small directory. Similarly, copying a small text file will complete faster compared to copying a high-quality movie.
Sometimes a user will not want to wait for a command to complete and would like to continue doing other stuff in the meantime. There are multiple ways to achieve this:
– Execute your command with ‘&’ appended to it. This makes sure that the command is run in the background while the terminal is freed up immediately.
– For an already running command not executed with an appended &, stop the command using Ctrl+Z and then run the ‘bg’ command to push it into background.
Other important points :
– To list all the commands running in the background, use the command ‘jobs’.
– To bring back a command running in the background to the foreground, use the
‘fg’ command.
– If there are multiple commands running in the background, you can use the job ID (listed in the output of the ‘jobs’ command) with the ‘fg’ command to bring a specified command to the foreground.
For example, here is an executable named ‘binary’ that runs infinitely.
$ ./binary
Now, to push this command to the background, use Ctrl+Z followed by the ‘bg’ command.
$ ./binary
^Z
[1]+ Stopped
binary
$ bg
[1]+ ./binary &
$
Observe that the command prompt is freed now while the command ‘binary’ is pushed to run in the background.
Now, to check if it is running in the background, use the ‘jobs’ command.
$ jobs
[1]+ Running
binary &
Observe that the output shows the command ‘binary’ and the state in which it is running.
To bring it back to foreground, use the ‘fg’ command.
$ fg
./binary
So, you can see that the command execution of ‘binary’ comes to the foreground.
Sometimes while working with a Q3: long command, I need to move here and there to change or correct some options. Using arrow keys seems to take quite a bit of time. Is there any shortcut to traverse whole words at a time?
Yes, shortcuts exist for traversing a command word by word, both forwards and backwards. Use the combination of Ctrl + ‘right arrow key’ to move forward (one word at a time), or Ctrl + ‘left arrow key’ to move backwards (one word at a time) on command line.
Is there any shortcut to run a previously run command with
root privileges?

Yes. You can refer to last run command with ‘!!’ and use sudo before it.
$ find / -name “abc”
find: `/media/himanshu’: Permission denied
find: `/root’: Permission denied
find: `/run/udisks2’: Permission denied
find: `/run/lightdm’: Permission denied
find: `/run/wpa_supplicant’: Permission denied
find: `/run/cups/certs’: Permission denied
As you can see in the above example, we tried using the ‘find’ command to search for a file named ‘abc’, but it started giving ‘permission denied’ errors as it could not access certain locations on the system. Now, to rerun this command with root privileges, we use the following shortcut:
$ sudo !!
sudo find / -name “abc”
[sudo] password for himanshu:
So you can see that using ‘sudo’ with ‘!!’ placed sudo prior to the previously run command. This trick is particularly useful when the command being run is complex or long.
What are some shortcuts through which I can speed up
my work on the command line?

Here are a few command-line shortcuts:
Sometimes while working with long commands, you need to move the cursor to the start or end of the command. The traditional method of using arrow keys seems very slow in these cases. The faster alternative is to press Ctrl+A to send the cursor to start of the command, or Ctrl+E to send the cursor to the end of the command.
Writing names for existing files or directories while on the command line can be made faster by using the Tab key extensively. Just type in the starting few characters from the name of the file and then hit Tab. If these characters match only a single existing file or folder, the name will get autocompleted for you; otherwise options are displayed, in which case you can complete the name by typing a few more characters (to make the these initial characters unique) and hitting Tab again.
Everybody knows that the ‘clear’ command can be used to clear the terminal screen, but for this you have to type and run this command from the prompt. If you do not want to run the clear command, Ctrl+L can be used to clear the screen while retaining whatever was there on the current prompt.
Using the mouse on command line for cut-copy-paste operations is not always advised. A quick text cut on the command line can be achieved by using Ctrl+K (make sure to place cursor at the beginning of the text to cut), while paste can be done using Ctrl+Y.
Sometimes you may want to rerun a complex/long command that you executed a while ago. Usually we use the up and down arrow keys to search previously run commands. To speed things up, reverse search can be used. Just press Ctrl+R and write few characters from the start of command you’re looking for. If you still don’t get the required result, try pressing Ctrl+R repeatedly to loop through the results.
I want to know more about my Linux system. Where can I get
detailed information?

The best way to obtain information about your Linux system is by running the ‘uname’ command with various options. Here are the details of the available options…
Execute ‘uname’ without any options to display the kernel name:
$ uname -s
Linux
Execute ‘uname’ with the -r option to display the kernel release…
$ uname -r
3.8.0-23-generic
Execute ‘uname’ with the -v option to display the kernel version:
$ uname -v
#34-Ubuntu SMP Wed May 29 20:22:58 UTC 2013
Execute ‘uname’ with the -m option to display the machine hardware:
$ uname -m
x86_64
Execute ‘uname’ with the -o option to display the operating system:
$ uname -o
GNU/Linux
Sometimes I roam here and there in different directories but Q7: eventually want to come back to a certain directory. How do I make Shell remember a directory path?
For cases where you change only a single directory, you can go back to the previous directory using the command ‘cd-’.
$ pwd
/home/himanshu/Desktop
$ cd ../practice/
$ cd -
/home/himanshu/Desktop
$ pwd
/home/himanshu/Desktop
So, you can see that by using ‘cd-’, one can easily switch back to the last directory.
The above trick is fine, but in a real-world scenario we tend to hop between various directories and the final directory we want to get back to is not always the previous directory. In this case, the commands ‘pushd’ and ‘popd’ can be used.
$ pwd
/home/himanshu/Desktop
$ pushd .
~/Desktop ~/Desktop
$ cd ../practice/
$ cd /home/himanshu/
$ cd /home/
$ popd
~/Desktop
$ pwd
/home/himanshu/Desktop
You can see that a ‘pushd’ followed by a dot (.) – representing the current working directory, which was /home/himanshu/ Desktop in this case – was performed initially. This is the directory to which the user wants to come back eventually. Subsequently, many directories changes were made and then, when ‘popd’ was finally done, control switched back to the directory (/home/himanshu/Desktop) to which the user wanted to return.
What is special about files/ Q8: directories whose name begins
with a dot (.)?

There are certain files in Linux which store system-wide and user-specific configuration information. Usually these type of files start with a dot (.) and are kept hidden. This means that these files are not visible if you do a simple ‘ls’ in the directory where they reside.
$ ls
Desktop Documents Downloads
examples.desktop Music Pictures
practice Public Templates #test#
Videos
You can see in the above output that a simple ‘ls’ in a user’s home directory could not list any file whose name begins with a dot. But, this does not confirm that there are no such files present in the directory. To confirm, run ‘ls’ with the option -a.
$ ls -a
. .bashrc
Desktop examples.desktop .kde
Pictures #test# .Xauthority
.. .cache
.dmrc .gconf
.local practice .thunderbird .Xauthority.8NWRZW
.adobe .compiz Documents
gnome2 .macromedia
.profile Videos .Xauthority.THC0ZW
.bash_history .config Downloads
.gstreamer-0.10 .mozlla
Public .vim
errors
.bash_logout .dubs .emacs.d
.ICEauthority Music
Templates .viminfo .xsession-errors.old
So, you can see that there are lots of files present in this directory whose names begin with a dot. The reason why these files are hidden by default is because they are of little use for a normal user in his day-to-day work.
When I run ‘ls’ in a certain directory, I see files and directories in various colours. What do these colours mean?
Different colours are used so that a user can easily identify the type of files.
Colour support is added through the user- specific .bashrc file – specifically through the following code:
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval
“$(dircolors -b ~/.dircolors)” ||
eval “$(dircolors -b)”
alias ls=’ls –color=auto’
#alias dir=’dir –color=auto’
#alias vdir=’vdir –color=auto’
alias grep=’grep –color=auto’
alias fgrep=’fgrep –color=auto’
alias egrep=’egrep –color=auto’
fi
To decode colours, just run the following code on the command line:
$ dircolors -p
What is the difference between > and >> while using them on the
command line?

Both > and >> are used to redirect output to a file. The difference lies in the fact that > overwrites the existing content with new content while >> appends to existing content.
$ echo “Hi, this is test” > output
$ cat output
Hi, this is test
$ echo “Old Text is overwritten” > output
$ cat output
Old Text is overwritten
So, you can see that using > again and again on the same file overwrites the previous content in the file.
$ cat output
Old Text is overwritten
$ echo “Old Text is not overwritten
now” >> output
$ cat output
Old Text is overwritten
Old Text is not overwritten now
In this case you can see that by using >>, the new text is appended to the file.
Sometimes I experience problems Q11: reading long files using cat, as the text scrolls past the screen before I can read it. How can I stop this from happening?
Use ‘less’ in this case. All you need to do is run the ‘cat’ command in the following way:
$ cat [filename] | less
This will hold the output until you continuously press the Enter key on your keyboard. To exit from this mode, just press Q.
What if I want to read only the first or last few lines of a file?
You can use ‘head’ and ‘tail’ commands for this.
$ tail -5 output
/etc/brltty/en-nabcc.ttb
/etc/brltty/brl-al-abt_small.ktb
/etc/brltty/brl-al-abt_basic.kti
/etc/acpi/mediabtn.sh
/etc/fstab.d
The ‘tail’ command above displays the last five lines from the file ‘output’.
Through this command, you can also display the last ‘n’ bytes using the -c option:
$ tail -c10 output
c/fstab.d
So, you can see that last 10 bytes were displayed in the output.
Similarly, there is a ‘head’ command to display content from the beginning of a file. Here are some examples:
$ head -10 output
/boot/abi-3.8.0-19-generic
/boot/abi-3.8.0-23-generic
/boot/grub/i386-pc/search_label.mod
/sbin/acpi_available
/sbin/ip6tables
/sbin/e2label
/sbin/ntfslabel
/sbin/swaplabel
/sbin/iptables-save
/sbin/ip6tables-restore
$ head -c10 output
/boot/abi-
It seems that the ‘find’ and ‘locate’ commands do the same thing. What is the difference between the two?
Both the ‘find’ and ‘locate’ commands do the same job: search for files. However, there is a major difference between the two. The ‘find’ command actually searches for files on the disk, while the ‘locate’ command searches a database. This database is prepared through the ‘updatedb’ command.
Since ‘locate’ searches a database, it is faster in execution as compared to ‘find’, but the real problem with ‘locate’ is its dependency on the database. Suppose you introduce a new file at a specified location on the disk, but do not update the database read by the ‘locate’ command; in this case ‘locate’ would not be able to find the new file.
$ touch new_file
$ ls new_file
new_file
$ locate new_file
$ sudo updatedb
$ locate new_file /home/himanshu/practice/new_file
So, here you can see that the ‘locate’ command was not able to find new_file until its database was updated using the ‘updatedb’ command.
A similar problem would occur if you removed a file from disk but failed to update the database. The ‘locate’ command will continue showing the file in its search results until the database is updated.
$ rm new_file
$ ls new_file
ls: cannot access new_file: No such file or directory
$ locate new_file /home/himanshu/practice/new_file
$ sudo updatedb
$ locate new_file
So, you can see that even after the file new_file was removed, the ‘locate’ command kept showing a non-existent file in its search results until the database was updated again.
What if I want to shut down or restart my Linux box from the command line only?
You can use the ‘shutdown’ and ‘reboot’ commands for shutting it down or restarting it.
Besides these commands, you can change the system runlevels using the ‘init’ command, to halt or restart the system. Runlevel 0 can be used to halt the system: ($init 0). And runlevel 6 can be used to restart the system:($init 6).

No comments:

Post a Comment