linux terminal commands

Program 1. Showing System Date and Time.

 

1.     $ Cal

2.     $ Cal jul 2015

3.     $ Clear

4.     $ Date

5.     Custom Format Output

There are several switches, you can use to format the output of date command.

6.     Get date time in “MM/DD/YY HH:MM:SS” format:

7.     $ date +"%D %T"

03/25/17 14:40:32

8.     Get date time in “YYYY-MM-DD HH:MM:SS” format:

9.     $ date +"%Y-%m-%d %T"

2019-03-25 14:40:32

10.  Here are more common date time formats:

Parameter

Output

date +”%m/%d/%Y”

03/25/2019

date +”%d-%b-%Y”

25-Mar-2019

date +”%Y %b %m”

2019 Mar 25

date +”%H:%M”

14:40

date +”%I:%M %p”

02:40 PM

date +”%H:%M:%S”

14:40:32

date +”%I:%M:%S %p”

02:40:32 PM

date +”%m/%d/%Y %H:%M”

03/25/2019 14:40

date +”%A, %m %d %Y %H:%M”

Monday, 03 25 2019 14:40

date +”%A, %b %d, %Y %I:%M %p”

Monday, Mar 25, 2019 02:40 PM

date +”%A, %b %d, %Y %H:%M:%S”

Monday, Mar 25, 2019 14:40:32

 

Program 2: Creating Files and Directory. Rename, Delete Files and Directories.

1.     $ pwd (showing current directory)

2.     $ touch hello (Creating file)

3.     $ cd Desktop

4.     $ pwd (showing current directory)

5.     $ touch hello (Creating file)

6.     $ touch hello{1..10}(creating multiple files)

7.     $ mv hello new (rename)

8.     $ rm new (delete file)

9.     $ mkdir new(creating directory)

10.  $ cd new(entering in new directory)

11.  $ cd ..(returning in Desktop)

12.  $ rm -r new(delete directory)

13.  $ mkdir hello

14.  $ touch file

15.  $ mv file /home/administrator name/Desktop/hello (move file to directory)

 

 

Program 3: Creating Text Files, Merge and View.

1.     $ cd Desktop

2.     $ cat > abc (creating files)

3.     Hello NITER (Typing text)

4.     $ cat > cde

5.     Hello LINUX

6.     $ cat abc cde > new (merging text in new file named new)

 

Program 4: Creating Copies, Links to Files and Directories.

7.     $ cd Desktop

8.     $ touch abc

9.     $ mkdir new(creating directory)

10.  $ cp abc new

11.  $ cp abc new/hello(rename)

12.  $ touch bd

13.  $ ln bd ef (bd file linkd to ef file)

How to run C program in UBUNTU…….

 

Confirm your installation by checking for GCC version by the command: gcc --version

Install build-essential by the command:

sudo apt install gcc

 

Crate file:

 

$ cd Desktop

$ touch hello.c

$ gedit hello.c

$ gcc hello.c(file name)

To compile the code within hello.c file, compile and execute it:

$ gcc hello.c -o hello

$ ./hello

Hello, World!

 

 

OKEY Now you are ready to Run any kind of c program in ubuntu…………

 

Lets make a try…….

 

 

 

 

 

 

 

1.     Fork() system call

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

#include <stdlib.h>

#include <errno.h>

#include <sys/wait.h>

int main()

{

printf("Parent process, pid = %u\n",getpid());

}

 

Next Step: Use fork(); before printf().

Here fork() function creates the child process.

Now add two more fork(); functions.

Now tell me what is happening……………

(This program executes 8times!!!!!! Right?????)

EXPLAIN……..

 

 

 

 

2.     Exec() system call

(For ex1.c file)

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

 

Int main(int a, char *ab[])

{

printf(“ pid of ex1.c=%d\n”, getpid());

Char *ac[]={“hello”,”world”,NULL};

Execv(“./ex2”, ac);

Printf(“back to ex1.c”);

}

 

(For ex2.c file)

 

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

 

Int main(int a, char *ab[])

{

printf(“ we are in ex2.c\n”);

printf(“ pid of ex2.c=%d\n”, getpid());

}

 

 

Now compile ex1.c file.

Explain what is happening……..

 

 

 

 

 

 

 

 

 

 

 

 

 

 

LAB-4

This sequence of characters (#!) is called shebang and is used to tell the operating system which interpreter to use to parse the rest of the file.

 

Shebang Interpreter Directive

The Shebang interpreter directive takes the following form:

 

#!interpreter [arguments]

 

The directive must be the first line in the script.

The directive must start with shebang #!

White space after the shebang characters is optional.

Interpreter is the full path to a binary file (ex: /bin/sh, /bin/bash).

Interpreter arguments are optional.

Examples:

 

#!/bin/bash - Uses bash to parse the file.

#!/usr/bin/env perl - Uses the env command to find the path to the perl executable.

#!/usr/bin/python Executes the file using the python binary.

Using Shebang in Bash Scripts

If a shebang is not specified and the user running the Bash script is using another Shell the script will be parsed by whatever the default interpreter is used by that Shell. For example, the default interpreter for bash is bash and for zsh is sh. To ensure that your script will always be interpreted with Bash you’ll need to specify the executable path using shebang.

 

There are two ways to use the Shebang directive and set the interpreter.

 

Using the absolute path to the bash binary:

 

#!/bin/bash

 

Using the env utility:

 

#!/usr/bin/env bash

 

 

Shell Script

A shell script is a computer program designed to be run by the Unix/Linux shell which could be one of the following:

The Bourne Shell

The C Shell

The Korn Shell

The GNU Bourne-Again Shell

A shell is a command-line interpreter and typical operations performed by shell scripts include file manipulation, program execution, and printing text.

Shell scripting is interpreted not compiled

 

Open terminal    //Ctrl+Alt+t

cat /etc/shells    //to check which shell your OS supports

You will get output like this

/bin/sh               //bourne shell

/bin/dash          

/bin/bash           //bourne again shell, improved of bourne

/bin/rbash

 

which bash        //where bash is located

/bin/bash           //location of bash

 

cd Desktop        //create folder in desktop

touch hello.sh   //create new file named hello, extension .sh indicates it’s a shell scripting file, but it’s not                                                           mandatory

ls -al                               //to see the permissions. You will see like this: -rw -rw -r. This means you have permission to read, write; the group has rw and user has read only, later we will see what is this

 

 

Editors: vem, nano, Visual studio code, default editor

if you double click on the script file, default editor will be opened. To open the directory in VS code type -

code .

 

#! /bin/bash       //to let the interpreter to know which shell it is

 

echo “Hello World”      //works like printf

.hello/sh

access denied    //will show this

chmod +x hello.sh        //use this to change the permission from read only

ls -al

./hello.sh

Hello World      //now you can see the output

 

Variables

System variables (written in upper case usually)

User defined variable (written in lower case usually)

 

Echo “Hello World”

echo $BASH                              //system variable

Output:

Hello World

/bin/bash

 

Other system variables: $BASH_VERSION, $PWD, $HOME

echo Our shell name is $BASH

echo Our home directory is $ HOME

How to define a variable

name=Sakib

echo $name

echo The name of the CR is $name

Output:

The name of the CR is Sakib

 

10val=10

echo $10val

echo value $10val

Output:

Valu 0val

not the right output, so like other languages starting with a number is not a valid variable name

VALUE=10

echo value is $VALUE

Output:

value is 10

 

User input

Single variable

echo “Enter name: “

read name         //variable name is name

echo “Given name is $name

 

Multiple variables

echo “Please enter three names: “

read name1 name2 name3          //give space between variables

echo “The names are: $name1, $namne2, $name3”

LAB-5

 

Rules for defining variables in Bash Scripts are as follows –

 

Variable names can contain uppercase, lowercase letters, numbers, underscores, and digits.

It is a good practice to use uppercase letters for variable names within Bash scripts.

Space is not allowed.

Pre-defined keywords cannot be used. Like if, else, etc.

The simplest example of the use of variables in Bash scripting can be given as –

 

Example Script:

 

NAME="SS"

echo "My name is $NAME"

 

 

Output:

 

My name is SS

 

 

The above example shows a variable ‘name‘. Then it is used with an echo command to display its value. So, the basic syntax for writing variables within a Bash Script will be –

 

Syntax of Writing Variables:

 

VariableName=value

echo $VariableName #for accessing the value

 

 

If we want to change the value of a variable then we can do that. The basic syntax for that will be –

 

VariableName=value

VariableName=newValue

echo $VariableName #for accessing the value

 

 

Below is an example of the same –

 

Example Script:

 

AGE=10 #assigning a value

AGE=20 #changing the value

echo $AGE #display the value

 

 

Output:

 

20

 

Operations on Variables

We can perform both numerical and string operations on variables on Bash scripting. An example of the same is given below –

 

Example Script:

 

NUM1=10 #variable 1

NUM2=5 #variable 2

 

# Numerical Operations over the variables

SUM=$(( $NUM1 + $NUM2 ))

SUBTRACT=$(( $NUM1 - $NUM2 ))

MULTIPLY=$(( $NUM1 * $NUM2 ))

DIVIDE=$(( $NUM1 / $NUM2 ))

 

echo "Addition : $SUM"

echo "Subtraction : $SUBTRACT"

echo "Multiply : $MULTIPLY"

echo "Divide : $DIVIDE"

 

# String Operations over the variables

NAME="GeeksforGeeks"

echo ${NAME:0:5} #substring extraction

 

FIRST_NAME="Isaac"

LAST_NAME="Newton"

echo ${FIRST_NAME}" "${LAST_NAME}

 

 

Output of Operations on Variables:

 

Addition : 15

Subtraction : 5

Multiply : 50

Divide : 2

Geeks

Isaac Newton

 

 

 

if Statement #

 

Bash if conditionals can have different forms. The most basic if statement takes the following form:

 

if TEST-COMMAND

then

  STATEMENTS

fi

 

The if statement starts with the if keyword followed by the conditional expression and the then keyword. The statement ends with the fi keyword.

 

If the TEST-COMMAND evaluates to True, the STATEMENTS gets executed. If TEST-COMMAND returns False, nothing happens; the STATEMENTS get ignored.

 

In general, it is a good practice always to indent your code and separate code blocks with blank lines. Most people choose to use either 4-space or 2-space indentation. Indentations and blank lines make your code more readable and organized.

 

Let’s look at the following example script that checks whether a given number is greater than 10:

 

#!/bin/bash

 

echo -n "Enter a number: "

read VAR

 

if [[ $VAR -gt 10 ]]

then

  echo "The variable is greater than 10."

fi

 

Save the code in a file and run it from the command line:

 

$ bash test.sh

 

The script will prompt you to enter a number. If, for example, you enter 15, the test command will evaluate to true because 15 is greater than 10, and the echo command inside the then clause will be executed.

 

The variable is greater than 10.

 

if..else Statement

The Bash if..else statement takes the following form:

 

if TEST-COMMAND

then

  STATEMENTS1

else

  STATEMENTS2

fi

 

If the TEST-COMMAND evaluates to True, the STATEMENTS1 will be executed. Otherwise, if TEST-COMMAND returns False, the STATEMENTS2 will be executed. You can have only one else clause in the statement.

 

Let’s add an else clause to the previous example script:

 

#!/bin/bash

 

echo -n "Enter a number: "

read VAR

 

if [[ $VAR -gt 10 ]]

then

  echo "The variable is greater than 10."

else

  echo "The variable is equal or less than 10."

fi

 

If you run the code and enter a number, the script will print a different message based on whether the number is greater or less/equal to 10.

 

if..elif..else Statement

 

The Bash if..elif..else statement takes the following form:

 

if TEST-COMMAND1

then

  STATEMENTS1

elif TEST-COMMAND2

then

  STATEMENTS2

else

  STATEMENTS3

fi

 

If the TEST-COMMAND1 evaluates to True, the STATEMENTS1 will be executed. If the TEST-COMMAND2 evaluates to True, the STATEMENTS2 will be executed. If none of the test commands evaluate to True, the STATEMENTS2 is executed.

 

You can have one or more elif clauses in the statement. The else clause is optional.

 

The conditions are evaluated sequentially. Once a condition returns True, the remaining conditions are not performed, and program control moves to the end of the if statements.

 

Let’s add an elif clause to the previous script:

 

#!/bin/bash

 

echo -n "Enter a number: "

read VAR

 

if [[ $VAR -gt 10 ]]

then

  echo "The variable is greater than 10."

elif [[ $VAR -eq 10 ]]

then

  echo "The variable is equal to 10."

else

  echo "The variable is less than 10."

fi

 

Nested if Statements

 

Bash allows you to nest if statements within if statements. You can place multiple if statements inside another if statement.

 

The following script will prompt you to enter three numbers and print the largest number among the three numbers.

 

#!/bin/bash

 

echo -n "Enter the first number: "

read VAR1

echo -n "Enter the second number: "

read VAR2

echo -n "Enter the third number: "

read VAR3

 

if [[ $VAR1 -ge $VAR2 ]]

then

  if [[ $VAR1 -ge $VAR3 ]]

  then

    echo "$VAR1 is the largest number."

  else

    echo "$VAR3 is the largest number."

  fi

else

  if [[ $VAR2 -ge $VAR3 ]]

  then

    echo "$VAR2 is the largest number."

  else

    echo "$VAR3 is the largest number."

  fi

fi

 

Here is how the output will look like:

 

Enter the first number: 4

Enter the second number: 7

Enter the third number: 2

7 is the largest number.

 

Generally, it is more efficient to use the case statement instead of nested if statements.

Multiple Conditions. The logical OR and AND operators allow you to use multiple conditions in the if statements.

 

Here is another version of the script to print the largest number among the three numbers. In this version, instead of the nested if statements, we’re using the logical AND (&&) operator.

 

#!/bin/bash

 

echo -n "Enter the first number: "

read VAR1

echo -n "Enter the second number: "

read VAR2

echo -n "Enter the third number: "

read VAR3

 

if [[ $VAR1 -ge $VAR2 ]] && [[ $VAR1 -ge $VAR3 ]]

then

  echo "$VAR1 is the largest number."

elif [[ $VAR2 -ge $VAR1 ]] && [[ $VAR2 -ge $VAR3 ]]

then

  echo "$VAR2 is the largest number."

else

  echo "$VAR3 is the largest number."

fi

 

Test Operators

 

In Bash, the test command takes one of the following syntax forms:

 

test EXPRESSION

[ EXPRESSION ]

[[ EXPRESSION ]]

 

To make the script portable, prefer using the old test [ command, which is available on all POSIX shells. The new upgraded version of the test command [[ (double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell.

 

To negate the test expression, use the logical NOT (!) operator. When comparing strings , always use single or double quotes to avoid word splitting and globbing issues.

 

Below are some of the most commonly used operators:

 

-n VAR - True if the length of VAR is greater than zero.

-z VAR - True if the VAR is empty.

STRING1 = STRING2 - True if STRING1 and STRING2 are equal.

STRING1 != STRING2 - True if STRING1 and STRING2 are not equal.

INTEGER1 -eq INTEGER2 - True if INTEGER1 and INTEGER2 are equal.

INTEGER1 -gt INTEGER2 - True if INTEGER1 is greater than INTEGER2.

INTEGER1 -lt INTEGER2 - True if INTEGER1 is less than INTEGER2.

INTEGER1 -ge INTEGER2 - True if INTEGER1 is equal or greater than INTEGER2.

INTEGER1 -le INTEGER2 - True if INTEGER1 is equal or less than INTEGER2.

-h FILE - True if the FILE exists and is a symbolic link.

-r FILE - True if the FILE exists and is readable.

-w FILE - True if the FILE exists and is writable.

-x FILE - True if the FILE exists and is executable.

-d FILE - True if the FILE exists and is a directory.

-e FILE - True if the FILE exists and is a file, regardless of type (node, directory, socket, etc.).

-f FILE - True if the FILE exists and is a regular file (not a directory or device).

 

The if, if..else and if..elif..else statements allow you to control the flow of the Bash script’s execution by evaluating given conditions.

 

Conditionals let us decide whether to perform an action or not, this decision is taken by evaluating an expression.

 

Expressions

An expression can be: String comparison, Numeric comparison, File operators and Logical operators and it is represented by [expression]:

String Comparisons: 

---------------------------------

=  compare if two strings are equal

!=  compare if two strings are not equal

-n  evaluate if string length is greater than zero

-z  evaluate if string length is equal to zero

 

Examples:

[ s1 = s2 ]  (true if s1 same as s2, else false)

[ s1 != s2 ]  (true if s1 not same as s2, else false)

[ s1 ]   (true if s1 is not empty, else false)

[ -n s1 ]   (true if s1 has a length greater then 0, else false)

[ -z s2 ]   (true if s2 has a length of 0, otherwise false)

 

Number Comparisons:

------------------------------------

-eq compare if two numbers are equal

-ge compare if one number is greater than or equal to a number

-le  compare if one number is less than or equal to a number

-ne  compare if two numbers are not equal

-gt  compare if one number is greater than another number

-lt  compare if one number is less than another number

 

Examples:

[ n1 -eq n2 ]  (true if n1 same as n2, else false)

[ n1 -ge n2 ]  (true if n1greater then or equal to n2, else false)

[ n1 -le n2 ]  (true if n1 less then or equal to n2, else false)

[ n1 -ne n2 ]  (true if n1 is not same as n2, else false)

[ n1 -gt n2 ]  (true if n1 greater then n2, else false)

[ n1 -lt n2 ]  (true if n1 less then n2, else false)

 

 

 

 

 

 

 

 

 

 

 

 

Post a Comment

0 Comments