Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Monday, 27 May 2024

Shell Scripting

 What is Shell?

Shell allows a user to interact with kernel and provide an environment to execute commands.

Types of Shell

  • bash
  • sh
  • ksh
  • tsh
  • fish
  • zsh
How to check your default shell?

poyadav@fedora:~$ echo $0
bash

What is shell scripting?
We can use shell scripting to automate tasks, it contains a set of commands to perform a task which are executed sequencially.

What is shebang?
#!/bin/bash 
It tell our system to use bash for executing the script.

How to execute as bash script?
  • ./file.sh    #Make sure file has execute command (chmod +x file.sh)
  • /path/file.sh  #Make sure file has execute command
  • bash file.sh
Variables
var=hello
var=$(command)
readonly var=value

Arrays
myarray=(1 2 3 "hello" "hii")   #contains space seperated values
echo "${myarray[2]}   #getting 3rd value
echo "${myarray[*]}   #gatiing all values
echo "${myarray[*]:2} #getting specific values

array+=(bye tata)  #adding new values

Key-Value arrays
declare -A myarray
myarray=( [name]=Henry [age]=23 ) 
echo "${myarray[name]}"

Strings Operations
myvar="Hello, how are you?"
length=${#myvar}
upper=${myvar^^}
lower=${myvar,,}
replace=${myvar/Hello/Hey}
slice=${myvar:2:5}

Getting input from user
echo -n "What is your name? "
read name
echo "Your name is $name"

read -p "What is your age? " age
echo "Your age is $age"

Arithmetic Operations
let a++
let a=6*10

((a++))
((a=6*10))


if-else 
if [ condition ];then
echo "PASS"
else
echo "FAIL"
fi

case
echo "where you want to go"
echo "a=Paris"
echo "b=London"
echo "c=USA"

read choice

case $choice in
a) echo "Going to Paris";;
b) echo "Going to London";;
c) echo "Going to USA";;
*) echo "Not going anywhere"
esac

Logical Operators
#Both conditions need to be true/met
if [[ condition1 ]] && [[ condition2 ]];then
echo "PASS"
else
echo "FAIL"
fi

#only one condition need to be true
if [[ condition1 ]] || [[ condition2 ]];then
echo "PASS"
else
echo "FAIL"

for Loop
for i in 1 2 3 4 5
do
echo i
done
#or we can also use
for i in Apple banana grapes
for i in {1..10}

#for loop with file
file=array.sh
for i in $(cat $file);do
echo $i
done

#or we can also use
for ((i=0;i<10;i++))
do
echo "Hello $i"
done

while Loop

#syntaX
count=0
num=10

while [ $count -lt $num ];do
echo "value is $count"
(( count++ ))
done

#reading from file
while read myvar;do
echo $myvar
done < myfile

#while with csv file
while IFS="," read id name age
do
echo "id is $id"
echo "name i $name"
echo "age is $age"
done < file.csv

Infinite Loop

while true;do
echo "Hey"
done
#for infinite loop
for (( ;; ));do
echo "Hey'
done

Functions

fun() {
echo "hello"
}
#another way
function myfun {
echo "Hey"
}

#function with args
myarg() {
echo "Hello $1"
echo "Welcome to $2"
}

fun
myfun
myarg raju manali
























Wednesday, 9 August 2023

SSH (Secure Shell)

 What is ssh?

SSH is a network protocol by which two machines can communicate with each other, we can transfer information or data from client and server in a secure way.

It uses encryption to secure the data that travel over the network to secure it.


Use of ssh:

We can access a remote machine using ssh over the same network.

Command: ssh <user>@<ip>  eg: ssh root@10.65.34.20

Now there are two types of authentication methods that we can use :

  1. Password-based authentication
  2. Key-based authentication
  • In Password-based authentication, we need the password of the host to access it.
  • In key-based authentication, we need keys on the machines ie private and public keys.

How to generate keys.

Command: ssh-keygen 

It generates two keys private key(id_rsa) and public key(id_rsa.pub) at ~/.ssh/

  • Private is private to our local machine, this should never be shared with others.
  • Public key can be shared with other servers/machines. We can copy our public key to a host/server using ssh-copy-id <user>@<ip> or if we can access the UI of the server, we can even upload it there as in GitLab, GitHub. 
The public keys are copied at  ~/.ssh/authorized_host on the server side. When we have our public key shared with the server, we don't need the password to access it, it will be passwordless login from the client. Authentication will be done on the key pair which we added earlier. 

 




Friday, 22 April 2016

Database with MySQL

MySQL is an open-source relational database management system(RDBMS). Before proceeding further one should have the knowledge of what exactly database is?

Database is a application that stores collection of data. Relational database management system is used to store and manage huge volume of data, all data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. Primary key is unique, and can not occur twice in one table and foreign key is the linking pin between two tables.
To use MySQL database, it is essential to become comfortable with mysql command  line.  So here are the basic commands which I went through to start with mysql database.
  • SHOW DATABASE - Used to view all available database.
  • USE <database name> - To work with specified database.
  • CREATE DATABASE <name> -  To create a new database.
  • DROP DATABASE <name> - To delete a database.
  • CREATE TABLE <name> - To create table.
  • SELECT command is used to view rows or column from a table.
  • WHERE command used to view only records that matches a specific condition, it can be with "greater than>", "less than<","not equal to!=" oe "equal to=". It can be used with OR, AND, NOT to combine multiple condition.
  • CONCAT function is used to combine values from multiple columns and display it. 
  • COUNT is used to display the total number of records in a table.
  • GROUP BY command is used to group records on certain conditions. There many more commands which we can understand more clearly only by using them.
So to see how these commands work I connected to MySQL server using MySQL client using mysql command, as it was already installed in system. After logging in successfully I created a new database for me named test, which I decided will contain different tables having student details, test detail, classes details,score details etc. Once my database was created I created various table inside it defining its parameters. Then I inserted the values to different tables according to the parameter defined by using INSERT command.
After doing this much of work I started playing with the tables by altering their name, by adding something new to them, by adding new column to them , by merging two columns and lots more things. It was a fun to extract different information by using various commands from different tables, and this is how I learned basics of MySQL.

Monday, 18 April 2016

A Day with IRC

IRC is mainly designed for group communication in discussion forums,called channels, it also allows one to one communication via private messages as well as chat. IRC is based on a client-server model. All you have to do is to run a client program on your computer which connects you to a server on the Internet. These servers link to many other servers to make up an IRC network,which transport messages from one user to another. For this only you need an Internet Service Provider to get you connected to the Internet and an IRC Client program.

After setting up with the provider and a client, you can choose a nickname of your choice and then connect different IRC networks. After going through the basic of IRC, I started with IRC and went through few commands and choosed a nickname (pyadav) for me. Then I joined few channels of my interest like dgplug, fedora-cloud, fedora-python etc.

You can find the channel of your interest with the /LIST command. After  finding the channel you can join it by using JOIN command as:   /JOIN #channelname - This changes your current channel to the specified channel and if the channel does not exist already, it will be created and you will be incharge of new channel.  To leave a channel you can use /LEAVE command. Private conversation can be done by /MSG command as  /MSG nickname <message>

Reference:


Monday, 4 April 2016

A New Beginning with Python

After making my mind to step into programming, the very first question that comes to my mind was "Which programming langauge must be learned to start with programming?" Then I hunted for which langauge should I start with being a beginner and ended up with 'Python' after a long research and conversation with my friends who already are in developing.

Python can become a stepping stone for everyone who want their career in programming universe as it was designed with newcomers in mind. It is easy to learn and grasp as the command are easy to remember because they are similar to the english words we use in our daily life. It is so simple, that you can start coding the very first day and make your own simple programs using python.

There are many more reasons I started with python as its a general purpose,
high level, interpreted language. The first code I leaned was how to print something in python, and it was so easy,I printed 'Hello World!' as it was the first code given in the book which I was referring ie  "Python for you and me".

>>> print "Hello World!"
Hello World!

"Python for you and me" was my first teacher to help me in learning Python (an interpreted , object oriented programming language) and helped me to get into python more and more with very new topics.

Also I joined the course of Udacity that is "Linux Command Line Basics" which was an introduction to the Linux Command Line interface and it
helped me in knowing more about the language and its basics. One thing I liked most about Udacity course is that we have different quizes followed by detailed solution after every topic. This keep us more involved in the course and makes it more interesting to learn and practice.The way of delivering each lesson was  just awesome, so it was worth joining that course.

After gaining enough knowledge about python I just started with some exercise having python programmes, and I found what I was looking for some good exercise of "Coding Bat" related to the topics which I have covered so far in Python.This helped me alot to brush up my concepts in programming.

Tuesday, 15 March 2016

Getting Started with Github

Github is a code hosting platform for version control and collaboration. It lets you and other work together on projects from anywhwere. It manage changes to a project without overwriting any part of that project and keeps a snapshot of every change ever made.
Having an overview of github I set up my username and email address, as every Git commit uses this information using the following commands
  $ git config --global username
  $ git config --global user.email

Before moving ahead I went through some words that are used in Git repeatedly like Repository, Version Control, Commit, Branch,etc.
As a beginner without going into too deep, I started with the basic commands for getting started with Git.

To create new git Repository I used "git init" command.
Local repository consists of three trees maintained by git.
Then I learned to add and commit using commands: 
       git add <filename>
       git commit -m "Commit message"
To push changes from HEAD to remote repository, I executed
     git push origin master
After getting started I find it interesting, then i jumped to other commands
like:
    git status
    git log
    git branch
    git branch <filename>
    git checkout <filename>
    git merge <filename>
    git  branch -d <filename>
    git log
    git push
    and many more.....

Practising these commands I am moving forward to get know more about Github through various tutorials and guides.
                                                             

                                                             

Tuesday, 8 March 2016

Experiment with Vim

A week ago, I switched to vim. Vim is the most popular editor. It is famous for been faster than other editor and helped me to improve my speed because now my hands rarely need to leave keyboard to perform different tasks.

Vim is a modal editor, its has different modes for inserting, editing, movement, commands, etc. Its three modes are:

- Command Mode
- Insert Mode
- Last Line Mode

Vim can be started by typing to terminal.
- $ vim

For inserting text, type i to enter insert mode and enter text. Type o to enter
insert mode and open line below cursor and O to open line above cursor.

Then I learnt about how to move around a file, when you are in command mode.
 -h moves the cursor one character left.
 -j moves the cursor down the line.
 -k moves the cursor up one line.
 -l moves the cursor one character to the right.
 -0 moves the cursor to the beginning of the line.
 -$ moves the cursor to the end of the line.
 -w move forward one word.
 -b move backward one word.
 -G move to the end of the file.
 -gg move to the beginning of the file.

Next I stepped to cut, copy, paste commands, practiced them and believe me they were easy.
  -e   edit some text at current cursor position
  -r   replace to with some new character
  -x,d delete a character
  -dw  delete a word
  -y   copy
  -p   paste
and many more......

  see line number-       :set nu
  go to particular line- :<line number>
  turn off line number-  :set nu!

Then I learnt about how to move around the files
 -ctrl+F -> Forward one screen
 -ctrl+B -> Scroll backward
 -ctrl+D -> Forward halfscreen
 -ctrl+U -> Backward halfscreen

Also I came through file splitting in vim
 :split -for horizontal split
 :vsplit-for vertical split

Now I'm stepping towards python which will help me to get started with programming.

Sunday, 6 March 2016

First baby step toward Linux

Past around 2 years I was working at iQor as a electronics engineer and wanted to give a chance to software industry and I heard about Linux (an open source operating system) which is a perfect platform if you want to start your career in software industry.

I wanted to switch to linux as its a commercial quality software to work with business documents, internet, networking, graphics etc. Also there are hundreds of free, high quality application which can be easily downloaded. So I moved ahead learning the basic commands used in Linux from hard way to learn shell.

The first command I learnt was pwd(print working directory) which is very helpful as it tells in which directory we are. It rescued me many times when I got lost amidst of directories in CLI(Command Line Interfece) while navigating.

Then I went through lot of commands as
- `mkdir`( Make A Directory) used to make directories
- `cd`( Change Directories) a way to navigate to a directory to check log, execute a program/application/script and for every other task.
- `ls` one of the most frequently used command in Linux to list files and directories (along with different options like -l, -a ... etc.).
- `rmdir` to delete directories but it fails if the directory contains files or subdirectories. So we use -p and -r options.
- `pushd` and `popd`, allow to manipulate the directory stack. It is used to change directories and return to the directory from which we came.
- `touch` command used to create empty files.
- `cp` to copy directories and cp - r for copying directories recursively.
- `mv` used to move or rename files.
- `cat` command used to create single or multiple files, view contain of file.
- `rm` to remove files, it doesn't remove directory with files in it, for this we have to recursively delete all of its content(rmdir -r)
- `find` command used to search and locate list of files and directories based on condition we specify for files that match the arguments.

Also learnt about Wildcards which commands can use to perform actions on more than one file at a time, or to find part of a phrase in a text file.

Next step will be learn more about CLI and vim (text editor) to get more exposure in Linux world.