Restart, Start, Stop MySQL through Command Line Terminal, OSX, Linux

Linux start/stop/restart

/etc/init.d/mysqld start
/etc/init.d/mysqld stop
/etc/init.d/mysqld restart

In some linux, run the following commond.

service mysqld start
service mysqld stop
service mysqld restart

or

service mysql start
service mysql stop
service mysql restart

 

In OS X,  to start/stop/restart MySQL pre 5.7 using command line:

sudo /usr/local/mysql/support-files/mysql.server start
sudo /usr/local/mysql/support-files/mysql.server stop
sudo /usr/local/mysql/support-files/mysql.server restart

 

In OS X Yosemite/El Capitan, to start/stop/restart MySQL using the command line:

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
sudo launchctl unload -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

Linux and Unix apt-get command

About apt-get

apt-get is the command-line tool for working with APT software packages.

APT (the Advanced Packaging Tool) is an evolution of the Debian .deb software packaging system. It is a rapid, practical, and efficient way to install packages on your system. Dependencies are managed automatically, configuration files are maintained, and upgrades and downgrades are handled carefully to ensure system stability.

Syntax

apt-get [-asqdyfmubV] [-o=config_string] [-c=config_file] [-t=target_release]
        [-a=architecture] {update | upgrade | dselect-upgrade | dist-upgrade |
        install pkg [{=pkg_version_number | /target_release}]... |
        remove pkg... | purge pkg... |
        source pkg [{=pkg_version_number | /target_release}]... |
        build-dep pkg [{=pkg_version_number | /target_release}]... |
        download pkg [{=pkg_version_number | /target_release}]... |
        check | clean | autoclean | autoremove | {-v | --version} |
        {-h | --help}}

Commands

download
update resynchronizes the local index of packages files, updating information about new and updated packages that are available. The indexes are fetched from the location(s) specified in /etc/apt/sources.list.

An update should always be performed before an upgrade or dist-upgrade.

upgrade installs the newest versions of all packages currently installed on the system, using the sources in /etc/apt/sources.list. If a package is currently installed and a new version is available, it is retrieved and upgraded. Under no circumstances are installed packages removed, or packages not already installed retrieved. New versions of currently installed packages that cannot be upgraded without changing the install status of another package will be left at their current version.

An update should always be performed first so that apt-get knows which new versions of packages are available.

dist-upgrade in addition to performing the function of upgrade, dist-upgrade also intelligently handles changing dependencies with new versions of packages; apt-get has a “smart” conflict resolution system, and it will attempt to upgrade the most important packages at the expense of less important ones if necessary.

The dist-upgrade command may therefore remove some packages.

The /etc/apt/sources.list file contains the list of locations package files will be retrieved from. See also apt_preferences for a mechanism that will override the general settings for individual packages.

dselect-upgrade used in conjunction with the traditional Debian packaging front-end, dselect. dselect-upgrade follows the changes made by dselect to the Status field of available packages, and performs the actions necessary to achieve that state (for instance, the removal of old and the installation of new packages).
install install installs one or more packages desired for installation or upgrading. Packages are specified by their package name, not a fully qualified filename (for instance, in a Debian system, “apt-utils” would be the argument provided, not “apt-utils_0.9.7.7ubuntu4_amd64.deb”). All packages required by the package(s) specified for installation will also be retrieved and installed. The /etc/apt/sources.list file is used to locate the desired packages.

If a hyphen is appended to the package name (with no intervening space), the identified package will be removed if it is installed. Similarly a plus sign can be used to designate a package to install. These annotation features may be used to override decisions made by apt-get’s default conflict resolution system.

A specific version of a package can be selected for installation by following the package name with an equals and the version of the package to select. This will cause that specific version to be located and installed. Alternatively, a specific distribution can be selected by following the package name with a slash and the version of the distribution or the Archive name (“stable”, “testing”, “unstable”).

Both of the version selection mechanisms can downgrade packages and must be used with care. You don’t want to manually remove a package that another installed package is dependent on.

If no package matches the given expression and the expression contains one of ‘.’, ‘?’ or ‘*’ then it is assumed to be a POSIX-style regular expression, and it is applied to all package names in the database. Any matches are then installed (or removed). (Note that matching is done by substring; so ‘lo.*’ matches ‘how-lo’ and also ‘lowest’. If this is undesired, anchor the regular expression with a ‘^’ or ‘$’ character, or create a more specific regular expression.

remove identical to install except that packages are removed instead of installed. Note that removing a package leaves its configuration files on the system. If a plus sign is appended to the package name (with no intervening space), the identified package will be installed instead of removed.
purge identical to remove except that packages are removed and purged (any configuration files are also deleted).
source causes apt-get to fetch source packages. APT will examine the available packages to decide which source package to fetch. It will then find and download into the current directory the newest available version of that source package while respecting the default release, as set with the option APT::Default-Release, the -t option or per package with the pkg/release syntax.

Source packages are tracked separately from binary packages via deb-src lines in the sources.list file.

If the –compile option is specified then the package will be compiled to a binary .deb using dpkg-buildpackage for the architecture as defined by the –host-architecture option. If –download-only is specified then the source package will not be unpacked.

A specific source version can be retrieved by postfixing the source name with an equals and then the version to fetch, similar to the mechanism used for the package files. This enables exact matching of the source package name and version, implicitly enabling the APT::Get::Only-Source option.

Note that source packages are not installed and tracked in the dpkg database like binary packages; they are simply downloaded to the current directory, like source tarballs.

build-dep causes apt-get to install/remove packages in an attempt to satisfy the build dependencies for a source package. By default the dependencies are satisfied to build the package natively. If desired a host-architecture can be specified with the –host-architecture option instead.
check a diagnostic tool; it updates the package cache and checks for broken dependencies.
downloads the given binary package into the current directory.
clean clears out the local repository of retrieved package files. It removes everything but the lockfrom /var/cache/apt/archives/ and /var/cache/apt/archives/partial/. When APT is used as a dselect method, clean is run automatically. If you don’t use use dselect you will likely want to run apt-get clean from time to time to free up disk space.
autoclean Like clean, autoclean clears out the local repository of retrieved package files. The difference is that it only removes package files that can no longer be downloaded, since they are largely useless. This allows a cache to be maintained over a long period without it growing out of control. The configuration option APT::Clean-Installed will prevent installed packages from being erased if it is set to off.
autoremove autoremove is used to remove packages that were automatically installed to satisfy dependencies for other packages and are now no longer needed.
changelog downloads a package changelog and displays it through sensible-pager. The server name and base directory is defined in the APT::Changelogs::Server variable. By default it displays the changelog for the version that is installed. However, you can specify the same options as for the install command.

Options

All command line options may be set using the configuration file; the descriptions indicate the configuration option to set. For boolean options you can override the config file by using something like -f-,–no-f, or -f=no.

–no-install-recommends Do not consider recommended packages as a dependency for installing.

Configuration Item: APT::Install-Recommends.

–install-suggests Consider suggested packages as a dependency for installing.

Configuration Item: APT::Install-Suggests.

-d, –download-only Download only; package files are only retrieved, not unpacked or installed.

Configuration Item: APT::Get::Download-Only.

-f, –fix-broken Fix; attempt to correct a system with broken dependencies in place. This option, when used with install/remove, can omit any packages to permit APT to deduce a likely solution. If packages are specified, these have to completely correct the problem. The option is sometimes necessary when running APT for the first time; APT itself does not allow broken package dependencies to exist on a system. It is possible that a system’s dependency structure can be so corrupt as to require manual intervention (which usually means using dselect or dpkg –remove to eliminate some of the offending packages). Use of this option together with -m may produce an error in some situations.

Configuration Item: APT::Get::Fix-Broken.

-m, –ignore-missing, –fix-missing Ignore missing packages; if packages cannot be retrieved or fail the integrity check after retrieval (corrupted package files), hold back those packages and handle the result. Use of this option together with -f may produce an error in some situations. If a package is selected for installation (particularly if it is mentioned on the command line) and it could not be downloaded then it will be silently held back.

Configuration Item: APT::Get::Fix-Missing.

–no-download Disables downloading of packages. This is best used with –ignore-missing to force APT to use only the .debs it has already downloaded.

Configuration Item: APT::Get::Download.

-q, –quiet Quiet; produces output suitable for logging, omitting progress indicators. More q’s will produce more quiet up to a maximum of 2. You can also use -q=# to set the quiet level, overriding the configuration file. Note that quiet level 2 implies -y; you should never use -qq without a no-action modifier such as -d, –print-uris or -s as APT may decide to do something you did not expect.

Configuration Item: quiet.

-s, –simulate, –just-print, –dry-run, –recon, –no-act No action; perform a simulation of events that would occur but do not actually change the system.

Configuration Item: APT::Get::Simulate.

Simulated runs performed as a user will automatically deactivate locking (Debug::NoLocking), and if the option APT::Get::Show-User-Simulation-Note is set (as it is by default) a notice will also be displayed indicating that this is only a simulation. Runs performed as root do not trigger either NoLocking or the notice; superusers should know what they are doing without further warnings from apt-get.

Simulated runs print out a series of lines, each representing a dpkg operation: configure (Conf), remove (Remv) or unpack (Inst). Square brackets indicate broken packages, and empty square brackets indicate breaks that are of no consequence, which is very rare.

-y, –yes, –assume-yes Automatic yes to prompts; assume “yes” as answer to all prompts and run non-interactively. If an undesirable situation, such as changing a held package, trying to install a unauthenticated package or removing an essential package occurs then apt-get will abort.

Configuration Item: APT::Get::Assume-Yes.

–assume-no Automatic “no” to all prompts.

Configuration Item: APT::Get::Assume-No.

-u, –show-upgraded Show upgraded packages; print out a list of all packages that are to be upgraded.

Configuration Item: APT::Get::Show-Upgraded.

-V, –verbose-versions Show full versions for upgraded and installed packages.

Configuration Item: APT::Get::Show-Versions.

-a, –host-architecture This option controls the architecture packages are built for by apt-get source –compile and how cross-builddependencies are satisfied. By default is it not set which means that the host architecture is the same as the build architecture (which is defined by APT::Architecture).

Configuration Item: APT::Get::Host-Architecture.

-b, –compile, –build Compile source packages after downloading them.

Configuration Item: APT::Get::Compile.

–ignore-hold Ignore package holds; this causes apt-get to ignore a hold placed on a package. This may be useful in conjunction with dist-upgrade to override a large number of undesired holds.

Configuration Item: APT::Ignore-Hold.

–no-upgrade Do not upgrade packages; when used in conjunction with install, no-upgrade will prevent packages on the command line from being upgraded if they are already installed.

Configuration Item: APT::Get::Upgrade.

–only-upgrade Do not install new packages; when used in conjunction with install, only-upgrade will install upgrades for already installed packages only and ignore requests to install new packages.

Configuration Item: APT::Get::Only-Upgrade.

–force-yes Force yes; this is a dangerous option that will cause apt to continue without prompting if it is doing something potentially harmful. It should not be used except in very special situations. Using force-yes can potentially destroy your system!

Configuration Item: APT::Get::force-yes.

–print-uris Instead of fetching the files to install, their URIs are printed. Each URI will have the path, the destination file name, the size and the expected MD5 hash. Note that the file name to write to will not always match the file name on the remote site! This also works with the source and update commands. When used with the update command the MD5 and size are not included, and it is up to the user to decompress any compressed files.

Configuration Item: APT::Get::Print-URIs.

–purge Use purge instead of remove for anything that would be removed. An asterisk (“*”) will be displayed next to packages which are scheduled to be purged. remove –purge is equivalent to the purge command.

Configuration Item: APT::Get::Purge.

–reinstall reinstall packages that are already installed and at the newest version.

Configuration Item: APT::Get::ReInstall.

–list-cleanup This option is on by default; use –no-list-cleanup to turn it off. When it is on, apt-get will automatically manage the contents of /var/lib/apt/lists to ensure that obsolete files are erased. The only reason to turn it off is if you frequently change your sources list.

Configuration Item: APT::Get::List-Cleanup.

-t, –target-release, –default-release This option controls the default input to the policy engine; it creates a default pin at priority 990 using the specified release string. This overrides the general settings in /etc/apt/preferences. Specifically pinned packages are not affected by the value of this option. In short, this option lets you have simple control over which distribution packages will be retrieved from. Some common examples might be -t ‘2.1*’, -t unstable or -t sid.

Configuration Item: APT::Default-Release.

–trivial-only Only perform operations that are ‘trivial’. Logically this can be considered related to –assume-yes; where –assume-yes will answer yes to any prompt, –trivial-only will answer no.

Configuration Item: APT::Get::Trivial-Only.

–no-remove If any packages are to be removed apt-get immediately aborts without prompting.

Configuration Item: APT::Get::Remove.

–auto-remove If the command is either install or remove, then this option acts like running the autoremove command, removing unused dependency packages.

Configuration Item: APT::Get::AutomaticRemove.

–only-source Only has meaning for the source and build-dep commands. Indicates that the given source names are not to be mapped through the binary table. This means that if this option is specified, these commands will only accept source package names as arguments, rather than accepting binary package names and looking up the corresponding source package.

Configuration Item: APT::Get::Only-Source.

–diff-only, –dsc-only, –tar-only Download only the diff, dsc, or tar file of a source archive.

Configuration Item: APT::Get::Diff-Only, APT::Get::Dsc-Only, and APT::Get::Tar-Only.

–arch-only Only process architecture-dependent build-dependencies.

Configuration Item: APT::Get::Arch-Only.

–allow-unauthenticated Ignore if packages can’t be authenticated and don’t prompt about it. This is useful for tools like pbuilder.

Configuration Item: APT::Get::AllowUnauthenticated.

-h, –help Show a short usage summary.
-v, –version Show the program version.
-c, –config-file Configuration File; Specify a configuration file to use. The program will read the default configuration file and then this configuration file. If configuration settings need to be set before the default configuration files are parsed specify a file with the APT_CONFIG environment variable. See apt.conf for syntax information.
-o, –option Set a Configuration Option; This will set an arbitrary configuration option. The syntax is -o Foo::Bar=bar. -o and –option can be used multiple times to set different options.

Files

/etc/apt/sources.list Locations to fetch packages from.

Configuration Item: Dir::Etc::SourceList.

/etc/apt/sources.list.d/ File fragments for locations to fetch packages from.

Configuration Item: Dir::Etc::SourceParts.

/etc/apt/apt.conf APT configuration file.

Configuration Item: Dir::Etc::Main.

/etc/apt/apt.conf.d/ APT configuration file fragments.

Configuration Item: Dir::Etc::Parts.

/etc/apt/preferences Version preferences file. This is where you would specify “pinning”, i.e. a preference to get certain packages from a separate source or from a different version of a distribution.

Configuration Item: Dir::Etc::Preferences.

/etc/apt/preferences.d/ File fragments for the version preferences.

Configuration Item: Dir::Etc::PreferencesParts.

/var/cache/apt/archives/ Storage area for retrieved package files.

Configuration Item: Dir::Cache::Archives.

/var/cache/apt/archives/partial/ Storage area for package files in transit.

Configuration Item: Dir::Cache::Archives (partial will be implicitly appended)

/var/lib/apt/lists/ Storage area for state information for each package resource specified in sources.list.

Configuration Item: Dir::State::Lists.

/var/lib/apt/lists/partial/ Storage area for state information in transit.

Configuration Item: Dir::State::Lists (partial will be implicitly appended)

Examples

Note: Many (if not most) apt-get operations require write access to the the APT lock file, which requires administrator privileges — so most commands listed here are prefixed with sudo, and require your password.

sudo apt-get install libc6

Install libc6, which comprises the shared libraries of the embedded GNU C library.

sudo apt-get remove chromium

Remove chromium, the Chromium web browser package.

sudo apt-get clean

Clean the local repository of downloaded package files, clearing disk space.

apt-get download ruby

Download the archive file for the package named ruby into the current directory. The file will have the .deb extension (in this case, ruby_x.x.x_all.deb). You could then install the package manually with dpkg –install.

Linux: Shell Scripting basics

Writing your first script and getting it to work

To successfully write a shell script, you have to do three things:

  1. Write a script
  2. Give the shell permission to execute it
  3. Put it somewhere the shell can find it

Writing a script

A shell script is a file that contains ASCII text. To create a shell script, you use a text editor. A text editor is a program, like a word processor, that reads and writes ASCII text files. There are many, many text editors available for your Linux system, both for the command line environment and the GUI environment. Here is a list of some common ones:

Name Description Interface
vi, vim The granddaddy of Unix text editors, vi, is infamous for its difficult, non-intuitive command structure. On the bright side, vi is powerful, lightweight, and fast. Learning vi is a Unix rite of passage, since it is universally available on Unix/Linux systems. On most Linux distributions, an enhanced version of the traditional vi editor called vim is used. command line
emacs The true giant in the world of text editors is emacs by Richard Stallman. emacs contains (or can be made to contain) every feature ever conceived for a text editor. It should be noted that vi and emacs fans fight bitter religious wars over which is better. command line
nano nano is a free clone of the text editor supplied with the pine email program. nano is very easy to use but is very short on features. I recommend nano for first-time users who need a command line editor. command line
gedit gedit is the editor supplied with the Gnome desktop environment. graphical
kwrite kwrite is the “advanced editor” supplied with KDE. It has syntax highlighting, a helpful feature for programmers and script writers. graphical

Now, fire up your text editor and type in your first script as follows:

#!/bin/bash
# My first script

echo "Hello World!"

If you have ever opened a book on programming, you would immediately recognize this as the traditional “Hello World” program. Save your file with some descriptive name. How about my_script?

The first line of the script is important. This is a special clue given to the shell indicating what program is used to interpret the script. In this case, it is /bin/bash. Other scripting languages such as perl, awk, tcl, Tk, and python can also use this mechanism.

The second line is a comment. Everything that appears after a “#” symbol is ignored by bash. As your scripts become bigger and more complicated, comments become vital. They are used by programmers to explain what is going on so that others can figure it out. The last line is the echo command. This command simply prints what it is given on the display.

Setting permissions

The next thing we have to do is give the shell permission to execute your script. This is done with the chmod command as follows:

[ub@linux ub]$ chmod 755 my_script

The “755” will give you read, write, and execute permission. Everybody else will get only read and execute permission. If you want your script to be private (i.e., only you can read and execute), use “700” instead.

Putting it in your path

At this point, your script will run. Try this:

[ub@linux ub]$ ./my_script

You should see “Hello World!” displayed. If you do not, see what directory you really saved your script in, go there and try again.

Before we go any further, I have to stop and talk a while about paths. When you type in the name of a command, the system does not search the entire computer to find where the program is located. That would take a long time. You have noticed that you don’t usually have to specify a complete path name to the program you want to run, the shell just seems to know.

Well, you are right. The shell does know. Here’s how: the shell maintains a list of directories where executable files (programs) are kept, and just searches the directories in that list. If it does not find the program after searching each directory in the list, it will issue the famous command not found error message.

This list of directories is called your path. You can view the list of directories with the following command:

[ub@linux ub]$ echo $PATH

This will return a colon separated list of directories that will be searched if a specific path name is not given when a command is attempted. In our first attempt to execute your new script, we specified a pathname (“./”) to the file.

You can add directories to your path with the following command, where directory is the name of the directory you want to add:

[ub@linux ub]$ export PATH=$PATH:directory

A better way would be to edit your .bash_profile file to include the above command. That way, it would be done automatically every time you log in.

Most modern Linux distributions encourage a practice in which each user has a specific directory for the programs he/she personally uses. This directory is called bin and is a subdirectory of your home directory. If you do not already have one, create it with the following command:

[ub@linux ub]$ mkdir bin

Move your script into your new bin directory and you’re all set. Now you just have to type:

[ub@linux ub]$ my_script

and your script will run.

Setup Apache Virtual Hosts on UBUNTU 14.04 LTS

Introduction

The Apache web server is the most popular way of serving web content on the internet. It accounts for more than half of all active websites on the internet and is very powerful and flexible. Apache breaks its functionality and components into individual units that can be customized and configured independently. The basic unit that describes an individual site or domain is called a virtual host.

These allow the admin to use one server to host multiple domains or sites off of a single interface or IP by using a matching mechanism. This is relevant to anyone looking to host more than one site off of a single VPS. Each domain that is configured will direct the visitor to a specific directory holding that site’s information, never indicating that the same server is also responsible for other sites. This scheme is expandable without any software limit as long as your server can handle the load.

Conditions

Before you start, you need to create non-root as explained in step 1 to 4 here.

You will need to have Apache installed server. If you have not, you need to use following command to install apache on server.

sudo apt-get update
sudo apt-get install apache2

 

Step 1.  — Create the Directory Structure

Document root (the top-level directory that Apache looks at to find content to serve) will be set to individual directories under the /var/www directory.

Within root directory, create public_html folder for site related files.

To create directory, user following commands

sudo mkdir -p /var/www/a2bizz.com/public_html

 

Step 2. — Access Permissions
sudo chown -R $USER:$USER /var/www/a2bizz.com/public_html

The $USER variable will take the value of the user you are currently logged in.

sudo chmod -R 755 /var/www

 

Step 3— Create IndexPage for Each Virtual Host
nano /var/www/a2bizz.com/public_html/index.html

index.html

<html>
  <head>
    <title>Welcome to A2bizz.com!</title>
  </head>
  <body>
    <h1>Success!  The awbizz.com virtual host is working!</h1>
  </body>
</html>

 

Step 4 — Create Virtual Host File

Apache comes with a default virtual host file called 000-default.conf that we can use as a jumping off point. We are going to copy it over to create a virtual host file for each of our domains.
Create the Virtual Host File

Copy conf file

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/a2bizz.com.conf

Edit a2bizz.com.conf file in editor

sudo nano /etc/apache2/sites-available/a2bizz.com.conf

The file look like,

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

First, we need to change the ServerAdmin directive to an email that the site administrator can receive emails through.

ServerAdmin admin@a2bizz.com

After this, we need to add two directives ( i.e. ServerNameServerAlias )

ServerName a2bizz.com
ServerAlias www.a2bizz.com

We need to change virtual host file is the location of the document root for domain.

DocumentRoot /var/www/a2bizz.com/public_html

Virtual host file should look like this:

<VirtualHost *:80>
    ServerAdmin admin@a2bizz.com
    ServerName a2bizz.com
    ServerAlias www.a2bizz.com
    DocumentRoot /var/www/a2bizz.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

save and close the file.

 

Step 5 — Enable the New Virtual Host Files

Use the a2ensite tool to enable the site.

sudo a2ensite a2bizz.com.conf

When you are finished, you need to restart Apache to make these changes take effect:

sudo service apache2 restart

You will most likely receive a message  something like following :

* Restarting web server apache2
 AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1. Set the 'ServerName' directive globally to suppress this messag

This is a harmless message that does not affect our site.

Step 6 — Set Up Local Hosts File
sudo nano /etc/hosts

Add ip as per domain name

127.0.0.1   localhost
127.0.1.1   guest-desktop
222.222.121.111 a2bizz.com

This will direct any requests for a2bizz.com on our computer and send them to our server at 222.222.121.111

save and close file.

Step 7— Test virtual host
http://a2bizz.com

Linux: Searching and Replacing string in multiple Files in a directory/ folder

I recently stuck into a condition in which I have to replace every occurrence of a certain word / string in a number of files spanning multiple directories, and this is the easiest way I found to do it. It uses grep to search for a certain word and if it find its it runs sed to replace the strings you want. Note: This will not work on windows systems

Basic Format

grep -rl 'stringToFind' /path/to/directory/where/files/are/saved | xargs sed -i 's/stringToFind/stringToReplace/g'
Note: The forward slash '/' delimiter in the sed argument could also be a different delimiter (pipe ‘|’ character). The pipe delimiter might be useful when searching through a lot of html files if you didn’t want to escape the forward slash, for instance.

Example

grep -rl 'room' ./ | xargs sed -i 's/room/house/g'

This will search for the string ‘room’ in all files relative to the current directory and replace ‘room’ with ‘house’ for each occurrence of the string in each file.