count-files-and-directories-in-linux

Ten command line time-savers for Linux administrators

Quick command line navigation and execution is the key to easy Linux system administration. Learn these 10 command line tricks to increase your proficiency and speed in Bash or other Linux shells.count-files-and-directories-in-linux

Although the Linux desktop has been subject to enormous improvements over the past twenty years (with perhaps the most notable change coming by way of the Ubuntu Unity interface), the command line remains unparalleled in terms of the power it can offer an experienced system administrator. Although most of the following 10 tips focus on the Bash shell, all of these tips will be easily applicable to other modern shells.

1. Create and enter a directory using one command



Creating and subsequently entering a new directory is such a common task it seems that there should be a shortcut for executing both commands in the shell. While it’s not, you can add the following function to your .bashrc file:

mkcd()
{
mkdir $1
cd $1
}

Then run source .bashrc to read the changes into memory, and complete both tasks using the mkcd command:

wjgilmore@ubuntu:~$ mkcd articles
wjgilmore@ubuntu:~/articles $

2. Return to the previous directory
When you need to move from a deeply embedded directory and want to return to the original directory you could pass the previous path into the cdcommand, but a little-known cd argument makes this trivial. This sequence demonstrates the behavior:

wjgilmore@ubuntu-laptop:~/Documents/techtarget_articles/ten_command_line_tricks/test2$ cd
wjgilmore@ubuntu-laptop:~$ cd -
~/Documents/techtarget_articles/ten_command_line_tricks/test2$
wjgilmore@ubuntu-laptop:~/Documents/techtarget_articles/ten_command_line_tricks/test2$

3. Creating directory bookmarks
Continuing along with the theme of directory interaction, there are some directories that you will inevitably return to time and again. It’s possible to create bookmarks that allow you to quickly navigate to those directories by adding their paths to the $CDPATH shell variable (within your .bashrc file):




CDPATH='.:/home/wjgilmore/books'

Once added, you can navigate directly to the books directory from anywhere within the operating system path simply by executing the following command:

$ cd books

4. Deftly edit the command line
How many times have you tediously edited and executed a series of slightly dissimilar commands? Such as when building the PDF version of various book chapters I’m working on from the Markdown source I regularly execute the following command:

$ pandoc -o html/chapter06.html chapters/chapter06.md  --template=templates/html.template

In order to also build the chapter04.md source document command line novices would quickly tire of arrowing up to retrieve the previously executed (above) command from history, and then arrowing left until replacing both instances of chapter06.md with chapter04.md. There are several more efficient ways to perform this task. First, consider using Bash’s command line editing keyboard shortcuts (two modes are supported: Emacs and vi), which allow you to quickly navigate to the desired location:




Ctrl + a: Go to beginning of line
Ctrl + e: Go to end of line
Alt + f: Go forward one word
Alt + b: Go backward one word

A second and even more efficient approach involves using command line substitution. The following command will replace the 06 found in the previously executed command with 04:

$ pandoc -o html/chapter06.html chapters/chapter06.md  --template=templates/html.template
$ !!:gs/06/04
pandoc -o html/chapter04.html chapters/chapter04.md  --template=templates/html.template

Incidentally if you’re using the GNOME terminal then the meta (Alt) key won’t work as described, because GNOME terminal already binds the Alt key to toolbar commands. Alternatively you can use Shift + Alt as the meta key, but this is a bit awkward. Instead, if you don’t require the toolbar command shortcuts, disable them by navigating to Edit -> Keyboard Shortcuts… and disable the Enable menu access keys option.

5. Saving a long command for later use
When working through a sequence of system administration operations, it is possible to type a particularly long command and then realize before executing it a step in the sequence has been left out. Rather than deleting the command, you can save it to the history without executing it by appending a hash mark (#) to the beginning of the command:

$ #this is some ridiculously long command that I want to save




After pressing the Enter button, arrow up and you’ll see the command has been saved. To execute the command, just remove the hash mark from the beginning of the line before execution.

6. Save typing using command aliases
The ls command’s long listing format (ls -l) can be frequently used, but the hyphen makes it a bit unwieldy when typing furiously. You can create command aliases of for longer commands using the alias command within .bashrc. In this example, the command alias dir is substituted for ls -l:

alias dir='ls -l'

7. Saving more typing by ignoring typos
You’re in the terminal zone, blazing from one directory to the next while copying, updating and removing files at will. Or you’re not, because the fingers are moving faster than the brain or even keyboard response time can handle, causing you to constantly backtrack and correct your typos. Add the following line to your .bashrc file and the shell will automatically fix any typing blunders you make when identifying file or path names.

shopt -s cdspell

8. Opening applications in the background
When cruising around the command line, you may need to do another task such as respond to an email. Of course, it’s possible to open GUI applications from the terminal in the same way you’d execute any other command, done simply by invoking their name, in this case, opening Gimp:

$ gimp

But doing so effectively ends your terminal session, because the application will open in the foreground. If you’re regularly opening a particular application from the command-line, consider modifying its default invocation within your .bashrc file:




gimp()
{
command gimp "$@" &
}

Reload your .bashrc file (see the source command) and you’ll be able to invoke the Gimp application, passing along the names of any image files you’d like to open, with the added bonus of retaining control of the terminal.

9. Do more with less
The more command is useful for quickly perusing the contents of a text file. Once the file is loaded into the page you can use the forward slash (/) to search the file. The problem is that once you’ve found the desired string it’s not possible to navigate up and inspect the contents that appeared prior to this string. The less command doesn’t suffer from this disadvantage, allowing you to scroll both up and down within a text file. The less command is invoked in the same manner as more:

$ less sometextfile.txt




10. Clean up your command line history
The history command is easily one of the most powerful tools at your disposal. But there is one timesaver in particular that deserves mention: the $HISTIGNORE shell variable.

Over time your history list will become incredibly long. Take advantage of the $HISTIGNORE ;variable to mute the recording of any commands you deem irrelevant:

$ export $HISTIGNORE="&:cd:exit:ls"

This will cause all duplicate commands, and the cd, exit, and ls commands to be omitted from the history list.

Speed is key to mastering the command line, and these ten tips and tricks should get you started on your command line mastery. If you would like to share any other tips, please contact me via my Web site.

Source http://searchenterpriselinux.techtarget.com

maxresdefault

Linux and Unix more command tutorial with examples

 

maxresdefaultWhat is the more command in UNIX?

The more command is a command line utility for viewing the contents of a file or files once screen at a time. It supports navigating forwards and backwards through a file and is primarily used for viewing the contents of a file. It also supports searching for strings or regular expressions and opening the file at the current point in a text editor.


How to view the contents of a file

To view the contents of a file pass the name of the file to more. This will open the file in more at the start of the file and fit the first page within the screen size available.

more /usr/share/dict/british
A
a
AA
AAA
Aachen
--More--(0%)





The line at the bottom shows that the file is being viewed within the moreprogram. As more moves through the file the percentage value on the bottom line will also update reflecting how far through the file the current page is.

How to view the contents of multiple files

To view the contents of multiple files using more pass the names of the files or a pattern to the more command. This will open a buffer for each file and show the first file. A banner is shown to indicate the file being shown.

more /usr/share/dict/*
::::::::::::::
/usr/share/dict/american-english
::::::::::::::
A

To move to the next file press :n. This moves the viewer to the start of the next file.

::::::::::::::
/usr/share/dict/british
::::::::::::::
A
a





To move back a file press :p. This moves to the start of the previous file.

How to navigate within more

To move forward a page within more the SPACE key may be used. Additionally the z key may be used. This moves forward a page based on the current screen size.

To move forward one line press the RETURN key. Optionally a number n may be pressed before the RETURN key to move forward by n lines.

To move backwards by a page press b or CTRL-B. Some versions of more support moving backwards by one line with the k key but your mileage may vary here.

How to open a file at a line number

To open a file at a line number pass the + option along with a line number

more +2654 /usr/share/dict/british





The more viewer will open at line 2654.

To open a file at the first occurrence of a search string pass the + option followed by a search pattern. The search pattern should begin with a / and can be a regular expression.

more +/^eat /usr/share/dict/british

The pager will move to the first occurrence of the search pattern.

How to search within more

To search within more press the / key followed by the phrase to be searched for. The search pattern accepts regular expressions. The following searches for the phrase ‘eat’. This will search lines for instances of the phrases and scroll the page to the first occurrence.

more /usr/share/dict/british
/eat

In this file the first occurrence is the word ‘aleatory’. To search for words starting with ‘eat’ a regular expression may be used.

more /usr/share/dict/british
/^eat

Now the word ‘eat’ is found.

To search for the next occurrence of a regular expresssion press the n key.


more /usr/share/dict/british
/eat
# first match is aleatory
# press 'n'
# second match is amphitheatre

How to display the file that more is viewing

To display the file that more is viewing press :f. The file will be shown at the bottom along with the current position in the file.

more /usr/share/dict/british :f “/usr/share/dict/british” line 34298

How to edit a file being viewed with more

To edit a file being viewed with more press v. This will launch the text editor that is set in the $EDITOR shell variable at the line being viewed. Once the file is save it returns to the more viewer. If no $EDITOR variable is found viwill be used.

To understand what the editor variable is echo it at a shell prompt. In the following example it is vim.

echo $EDITOR
vim





If the $EDITOR variable is not set or is set incorrectly it may be set temporarily as follows.

export EDITOR=vim

To set the $EDITOR variable permanently add the following to your .bashrcfile if you are using bash or .zshrc file if you are using zsh.

export EDITOR=vim

Getting help within more

To access the help menu press h within more.

How to exit more

To exit from more press q or Q. This returns you to the terminal prompt.

Further reading

Source https://shapeshed.com

install_web1

The Basics of Using the Sed Stream Editor to Manipulate Text in Linux

Introduction

The sed stream editor is a text editor that performs editing operations on information coming from standard input or a file. Sed edits line-by-line and in a non-interactive way.

This means that you make all of the editing decisions as you are calling the command and sed will execute the directions automatically. This may seem confusing or unintuitive, but it is a very powerful and fast way to transform text.




This tutorial will cover some basics operations and introduce you to the syntax required to operate this editor. You will almost certainly never replace your regular text editor with sed, but it will probably become a welcomed addition to your text editing toolbox.

Basic Usage

In general, sed operates on a stream of text that it reads from either standard input or from a file.

This means that you can send the output of another command directly into sed for editing, or you can work on a file that you’ve already created.

You should also be aware that sed outputs everything to standard out by default. That means that, unless redirected, sed will print its output to the screen instead of saving it in a file.

The basic usage is:

sed [options] commands [file-to-edit]

We will copy some files into our home directory to practice some editing.


cd
cp /usr/share/common-licenses/BSD .
cp /usr/share/common-licenses/GPL-3 .

Let’s use sed to view the contents of the BSD license file we copied.

Since we know that sed sends its results to the screen by default, we can use it as a file reader by passing it no editing commands. Let’s try it:

sed '' BSD
Copyright (c) The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
...
...





This works because the single quotes contain the editing commands we are passing to sed. We passed it nothing, so it just printed each line it received to standard output.

We will demonstrate how sed can use standard input by piping the output of the “cat” command into sed to produce the same result.

cat BSD | sed ''
Copyright (c) The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
. . .
. . .

As you can see, we can operate on files or streams of text (as is produced when piping output with the “|” character) just as easily.

Printing Lines

In the previous example, we saw that input passed into sed without any operations would print the results directly to standard output.




We will now explore sed’s explicit “print” command, which is specified by using the “p” character within single quotes.

sed 'p' BSD
Copyright (c) The Regents of the University of California.
Copyright (c) The Regents of the University of California.
All rights reserved.
All rights reserved.


Redistribution and use in source and binary forms, with or without
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
modification, are permitted provided that the following conditions
are met:
are met:
. . .
. . .

You can see that sed has printed each line twice now. This is because it automatically prints each line, and then we’ve told it to print explicitly with the “p” command.

If you examine how the output has the first line twice, followed by the second line twice, etc., you will see that sed operates line by line. It accepts a line, operates on it, and outputs the resulting text before repeating the process on the next line.




We can clean up the results by passing the “-n” option to sed, which suppresses the automatic printing:

sed -n 'p' BSD
Copyright (c) The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
. . .
. . .

We now are back to printing each line once.

Address Ranges

The examples so far can hardly be considered editing (unless we wanted to print each line twice…). Let’s modify the output by only having sed print the first line.

sed -n '1p' BSD
Copyright (c) The Regents of the University of California.

By placing the number “1” before the print command, we have told sed the line number to operate on. We can just as easily print five lines (don’t forget the “-n”).

sed -n '1,5p' BSD
Copyright (c) The Regents of the University of California.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions

We’ve just given an address range to sed. If we give sed an address, it will only perform the commands that follow on those lines. In this example, we’ve told sed to print line 1 through line 5. We could have specified this in a different way with by giving the first address and then using an offset to tell sed how many additional lines to travel:

sed -n '1,+4p' BSD

This will result in the same output, because we’ve told sed to start at line 1 and then operate on the next 4 lines as well.




If we want to print every other line, we can specify the interval after the “~” character. The following line will print every other line starting with line 1:

sed -n '1~2p' BSD
Copyright (c) The Regents of the University of California.

modification, are permitted provided that the following conditions
1. Redistributions of source code must retain the above copyright
2. Redistributions in binary form must reproduce the above copyright
   documentation and/or other materials provided with the distribution.
   may be used to endorse or promote products derived from this software
. . .
. . .

Deleting Text

We can easily perform text deletion where we previously were specifying text printing by changing the “p” command to the “d” command.

We no longer need the “-n” command because with the delete command, sed will print everything that is not deleted, which will help us see what’s going on.

We can modify the last command from the previous section to make it delete every other line starting with the first. The result is that we should be given every line we were not given last time.

sed '1~2d' BSD
All rights reserved.
Redistribution and use in source and binary forms, with or without
are met:
   notice, this list of conditions and the following disclaimer.
   notice, this list of conditions and the following disclaimer in the
3. Neither the name of the University nor the names of its contributors
   without specific prior written permission.
. . .
. . .

It is important to note here that our source file is not being affected. It is still intact. The edits are output to our screen.

If we want to save our edits, we can redirect standard output to a file like so:

sed '1~2d' BSD > everyother.txt

If we open the file with cat, we will see the same output that we saw onscreen previously. Sed does not edit the source file by default for our safety.




We can change this behavior though by passing sed the “-i” option, which means perform edits in-place. This will edit the source file.

Let’s try it by editing our “everyother.txt” file we just created, in-place. Let’s further reduce the file by deleting every other line again:

sed -i '1~2d' everyother.txt

If you use cat again, you can see that the file has been edited.

As mentioned previously, the “-i” option can be dangerous! Thankfully, sed gives us the ability to create a backup file prior to editing.

To create a backup file prior to editing, add the backup extension directly after the “-i” option:

sed -i.bak '1~2d' everyother.txt

This will create a backup file with the “.bak” extension, and then edit the regular file in-place.

Substituting Text

Perhaps the most well-known use for sed is substituting text. Sed has the ability to search for text patterns using regular expressions, and then replace the found text.

In its simplest form, you can change one word to another word using the following syntax:

's/old_word/new_word/'

The “s” is the substitute command. The three slashes (/) are used to separate the different text fields. You can use other characters to delimit the fields if it would be more helpful.

For instance, if we were trying to change a website name, using another delimiter would be helpful since URLs contain slashes. We’ll use echo to pipe in an example:

echo "http://www.example.com/index.html" | sed 's_com/index_org/home_'
http://www.example.org/home.html

Do not forget the final delimiter, or sed will complain.

echo "http://www.example.com/index.html" | sed 's_com/index_org/home'
sed: -e expression #1, char 22: unterminated `s' command

Let’s create a file to practice our substitutions on:

echo "this is the song that never ends
yes, it goes on and on, my friend
some people started singing it
not knowing what it was
and they'll continue singing it forever
just because..." > annoying.txt

Now let’s substitute the expression “on” with “forward”.

sed 's/on/forward/' annoying.txt
this is the sforwardg that never ends
yes, it goes forward and on, my friend
some people started singing it
not knowing what it was
and they'll cforwardtinue singing it forever
just because...

You can see a few notable things here. First, is that we are replacing patterns, not words. The “on” within “song” is changed to “forward”.

The other thing to notice is that on line 2, the second “on” was not changed to “forward”.

This is because by default, the “s” command operates on the first match in a line and then moves to the next line.




To make sed replace every instance of “on” instead of just the first on each line, we can pass an optional flag to the substitute command.

We will provide the “g” flag to the substitute command by placing it after the substitution set.

sed 's/on/forward/g' annoying.txt
this is the sforwardg that never ends
yes, it goes forward and forward, my friend
some people started singing it
not knowing what it was
and they'll cforwardtinue singing it forever
just because...

Now the substitute command is changing every instance.

If we only wanted to change the second instance of “on” that sed finds on each line, then we could use the number “2” instead of the “g”.

sed 's/on/forward/2' annoying.txt
this is the song that never ends
yes, it goes on and forward, my friend
some people started singing it
not knowing what it was
and they'll continue singing it forever
just because...

If we only want to see which lines were substituted, we can use the “-n” option again to suppress automatic printing.

We can then pass the “p” flag to the substitute command to print lines where substitution took place.

sed -n 's/on/forward/2p' annoying.text
yes, it goes on and forward, my friend

As you can see, we can combine the flags at the end of the command.

If we want the search process to ignore case, we can pass it the “i” flag.

sed 's/SINGING/saying/i' annoying.txt
this is the song that never ends
yes, it goes on and on, my friend
some people started saying it
not knowing what it was
and they'll continue saying it forever
just because...

Referencing Matched Text

If we wish to find more complex patterns with regular expressions, we have a number of different methods of referencing the matched pattern in the replacement text.

For instance, if we want to match the from the beginning of the line to “at” we can use the expression:

sed 's/^.*at/REPLACED/' annoying.txt
REPLACED never ends
yes, it goes on and on, my friend
some people started singing it
REPLACED it was
and they'll continue singing it forever
just because...

You can see that the wildcard expression matches from the beginning of the line to the last instance of “at”.

Since you don’t know the exact phrase that will match in the search string, you can use the “&” character to represent the matched text in the replacement string.

This example shows how to put parentheses around the matched text:

sed 's/^.*at/(&)/' annoying.txt
(this is the song that) never ends
yes, it goes on and on, my friend
some people started singing it
(not knowing what) it was
and they'll continue singing it forever
just because...

A more flexible way of referencing matched text is to use escaped parentheses to group sections of matched text.

Every group of search text marked with parentheses can be referenced by an escaped reference number. For instance, the first parentheses group can be referenced with “\1”, the second with “\2” and so on.

In this example, we’ll switch the first two words of each line:

sed 's/\([a-zA-Z0-9][a-zA-Z0-9]*\) \([a-zA-Z0-9][a-zA-Z0-9]*\)/\2 \1/' annoying.txt
is this the song that never ends
yes, goes it on and on, my friend
people some started singing it
knowing not what it was
they and'll continue singing it forever
because just...

As you can see, the results are not perfect. For instance, the second line skips the first word because it has a character not listed in our character set. Similarly, it treated “they’ll” as two words in the fifth line.

Let’s improve the regular expression to be more accurate:

sed 's/\([^ ][^ ]*\) \([^ ][^ ]*\)/\2 \1/' annoying.txt
is this the song that never ends
it yes, goes on and on, my friend
people some started singing it
knowing not what it was
they'll and continue singing it forever
because... just

This is much better than last time. This groups punctuation with the associated word.




Notice how we repeat the expression inside the parentheses (once without the “*” character, and then once with it). This is because the “*” character matches the character set that comes before it zero or more times.

This means that the match with the wildcard would be considered a “match” even if the pattern is not found.

To ensure that it is found at least once, we must match it once without the wildcard before employing the wildcard.

 Conclusion

We have covered just a few of the basics of sed. You should be able to see already how you can quickly transform a text document using properly constructed sed commands.

Source https://www.digitalocean.com

fixedbyvonnie-centos-viewing-bash-history-hidden-file

Linux: Bash Delete All Files In Directory Except Few

I‘m a new Linux system user. I need to cleanup in a download directory i.e. delete all files from ~/Downloads/ folders except the following types:

*.iso – All iso images files.
*.zip – All zip files.




How do I delete all file except some in bash shell on a Linux, OS X or Unix-like systems?

Bash shell supports rich file pattern matching such as follows:

  • * - Match any files.
  • ? - Matches any single character in filenames.
  • [...] - Matches any one of the enclosed characters.

Method #1: Say hello to extended pattern matching operators

You need to use the extglob shell option using the shopt builtin command to use extended pattern matching operators such as:


  1. ?(pattern-list) – Matches zero or one occurrence of the given patterns.
  2. *(pattern-list) – Matches zero or more occurrences of the given patterns.
  3. +(pattern-list) – Matches one or more occurrences of the given patterns.
  4. @(pattern-list) – Matches one of the given patterns.
  5. !(pattern-list) – Matches anything except one of the given patterns.

A pattern-list is nothing but a list of one or more patterns (filename) separated by a |. First, turn on extglob option:

shopt -s extglob

Bash remove all files except *.zip and *.iso files





The rm command syntax is:

## Delete all file except file1 ##
rm  !(file1)
 
## Delete all file except file1 and file2 ##
rm  !(file1|file2) 
 
## Delete all file except all zip files ##
rm  !(*.zip)
 
## Delete all file except all zip and iso files ##
rm  !(*.zip|*.iso)
 
## You set full path too ##
rm /Users/vivek/!(*.zip|*.iso|*.mp3)
 
## Pass options ##
rm [options]  !(*.zip|*.iso)
rm -v  !(*.zip|*.iso)
rm -f  !(*.zip|*.iso)
rm -v -i  !(*.php)

Finally, turn off extglob option:

shopt -u extglob

Method #2: Using bash GLOBIGNORE variable to remove all files except specific ones





From the bash(1) page:

A colon-separated list of patterns defining the set of filenames to be ignored by pathname expansion. If a filename matched by a pathname expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches.

To delete all files except zip and iso files, set GLOBIGNORE as follows:

## only works with BASH ##
cd ~/Downloads/
GLOBIGNORE=*.zip:*.iso
rm -v *
unset GLOBIGNORE

Method #3: Find command to rm all files except zip and iso files

If you are using tcsh/csh/sh/ksh or any other shell, try the following find command syntax on a Unix-like system to delete files:


find /dir/ -type f -not -name 'PATTERN' -delete

OR

## deals with weird file names using xargs ##
find /dir/ -type f -not -name 'PATTERN' -print0 | xargs -0 -I {} rm {}
find /dir/ -type f -not -name 'PATTERN' -print0 | xargs -0 -I {} rm [options] {}

To delete all files except php files in ~/sources/ directory, type:

find ~/sources/ -type f -not -name '*.php' -delete




OR

find ~/sources/ -type f -not -name '*.php' -print0 | xargs -0 -I {} rm -v {}

The syntax to delete all files except *.zip and *.iso is as follows:

Source http://www.cyberciti.biz

14-command-line-tips-tricks

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.
14-command-line-tips-tricks
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).

Source www.gadgetdaily.xyz