Operating Systems
Operating Systems
a. TZ
By default, “date” command uses the time zone defined in path “/etc/localtime”. Linux user can
change the time zone via Terminal by using command “TZ”.
Syntax: TZ=Name_of_Time_Zone date
Example:
TZ=GMT date
TZ=KSA date
b. –set
Linux allows its user to set the current date and time of the system manually.
Syntax: date –set=”Date_in_format(YYMMDD) Time_in_format(HH:MM)”
Example:
c. -d
To operate the system on a specific date, you can change the date by using “-d”.
Syntax: date -d Date_to_operate_system_on
Example:
date -d now
date -d yesterday
date -d tomorrow
date -d last-Sunday
date -d “1997-04-22”
df
The command “df” shows the amount of disk space used and disk space available on every file
system containing each filesystem’s name and its path.
Syntax: df
Example:
a. df -h
The command “df -h” shows the same result as the command “df” but now the data is in a more
human-readable form which can be easily comprehended by a new user.
Syntax: df -h
Example:
free
The command “free” displays the amount of free and used memory in the complete system.
Syntax: free
Example:
free
Ps
The command “ps” which is also known as process status command is used to provide information
about the processes currently running on the system, including their respective process identification
numbers (PIDs).
Syntax: ps
Example:
uptime
The command “uptime” provides information about how long the system has been running in one line.
Result for this command includes the current time, the time duration system has been running for, the
number of users who are currently logged on, and the system load averages for the past 1, 5, and 15
minutes respectively.
Syntax: uptime
Example:
w
The command “w” displays the detailed information about the users who are logged in the system
currently.
Syntax: w
Example:
passwd
The command “passwd” stands for password and it is used to change the password of the user.
Syntax: passwd user_name
Example:
passwd my_user
exit
The command “exit” as the name says it is used to exit from the system and log out from the current
user.
Syntax: exit
Example:
shutdown
The command “shutdown” is used to shut down the system.
Syntax: shutdown
Example:
mkdir NewDirectory
Entering the command “mkdir NewDirectory” will create the directory named as NewDirectory in the
current directory.
rmdir
The command “rmdir” allows users to remove directories/folders from the system. The user running
this command must have suitable rights over the parent directory to remove a directory or they will
receive an error.
Syntax: rmdir Directory’s_Name
Example:
rmdir NewDirectory
Entering the command “rmdir NewDirectory” will remove the directory named as NewDirectory in the
current directory.
rm
The command “rm” is used to remove files from the directory.
Syntax: rm file’s_name
Example:
rm Test_File
This above-mentioned command will remove the file “Test_File” from the Desktop directory.
mv
The command “mv” is used for two purposes
To move files or directories from one path to another path in the system.
To rename a file or folder.
a. “mv” to Move Files
Syntax: mv Source_File_name Destination_File_Name
Example:
Consider having two files in a directory (File1 and File2). Entering the command “mv File1 File2” will
move data of File1 to File2 and delete source file(i.e. File1) from the system.
cp
The command “cp” is used to copy data from a source file to the destination file. Its function is almost
like the command “mv”. The only difference is by using the command “cp” the source file is not
removed from the directory after its data is moved to the destination file.
Syntax: cp source_file_name destination_file_name
Example:
cp A B
Consider having two files (A and B) in Desktop Directory. Entering the command “cp A B” will copy all
the data from file A to file B and user can still access both files (A and B).
cat
The command “cat” is a reverse of the command “tac”. It is used to display each line of the file
starting from the first row and finishing on its last row.
cat Test_File
Consider having a file named Test_File as shown below, “cat” command will display its data on the
screen.
cat File1 File2
Consider having two files (File1 and File2) in the Desktop directory. Via above-mentioned cat
command, the User can display data from both the files on their screen.
head
The command “head” prints the top N rows of data of the given input or file. By default, it prints the
first 10 lines of the specified files.
Syntax:
head -n File_name
Example:
head -5 New_Test.txt
The above-mentioned command will only print first 5 rows of the file New_Test.txt
tail
The command “tail” prints the last N rows of data of the given input or file. By default, it prints the last
10 lines of the specified files.
Syntax:
tail -n File_name
Example:
tail -5 New_Test.txt
The above-mentioned command will only print last 5 rows of the file New_Test.txt.
echo
The command “echo” used to display any expression that is passed as an argument.
Syntax:
echo expression_to_be_displayed
Example:
echo user
grep “Are” B
The above-mentioned command will search for the word “Are” in the text of the file B.
zip
The command “zip” is used to compress one or more files and store them in a new file with .zip
extension.
The above-mentioned command will compress all three files (Check.txt, and Test.txt and Output.txt)
and store these in a new file which we’re creating through this command i.e. Files.zip.
unzip
The command “unzip” is used to decompress a .zip file and extract all the files within to current
directory.
Syntax: unzip zip_file_name.zip
Example:
unzip Files.zip
Consider having a zip File named as Files.zip with a compressed .txt file in it. The above-mentioned
command will help you unzip the file (Files.zip) and extract the .txt file from it to the current directory.
sudo
The command “sudo -I” is used to continue the session as a root user which has a lot more privileges
than normal system user.
Syntax: sudo -i
Example:
Basic Commands
history
The simple command “history” displays the list of all commands entered since the user started the
session.
Syntax: history
Example:
Note: To clear all the previous history use command “history -c”.
help
The command of “help” provides you help to learn about all the built-in commands.
Syntax: help
Example:
man
The command of “man” stands for manual and it is used to display the user manual of any built-in
Linux command.
Syntax: man command_name
Example:
man vim
This command displays the user manual of the built-in Linux command “vim”.
dir
The command “dir” stands for directory and it is used to display the list of all directories or folder in
the current directory.
Syntax: dir
Example:
ls
The command “ls” displays the list of all directories, folder, and files present in the current directory.
Syntax:
ls
Ls -ltr
Example:
ls
The above-mentioned command displays the name of directories, folders, and files
ls -ltr
The above-mentioned command displays the name of directories, folders, files with their respective
owner name, group’s name and rights your user have over these.
cd
The command “cd” stands for change directory and it is used to change the current directory user is
operating in via Terminal.
Syntax:
cd destination_directory’s_name (to move forward from your current directory to the next directory
within current directory)
cd .. (to move back in the previous directory from your current directory)
Example:
cd Desktop
This command takes you from Directory /home/user to the destination directory which is
/home/user/Desktop.
Note: You cannot only use cd when the destination directory is within your current directory.
cd ..
pwd
The command “pwd” displays the path of the current directory user is operating in via Terminal.
Syntax: pwd
Example:
clear
The command “clear” is to clear the screen of Terminal.
Syntax: clear
Example:
clear
Before
After
whereis
The command “whereis” is self-explanatory, as it displays the path where the package for specific
built-in Linux command locates.
whereis zip
whereis help
whereis cat
whatis
The command “whatis” is also self-explanatory, as it displays a brief description of what is the
functionality of specific built-in Linux command.
Syntax: whatis command_name
Example:
whatis cat
whatis help
whatis zip
With this, we wish you all the luck for your journey with Ubuntu! You will find the OS difficult initially,
however with the commands and instructions given above, you will save a lot of time. A strong grip
over the Linux Terminal is what makes the user dominant over the system.
Open any editor to create a bash file. Here, nano editor is used to create the file and
filename is set as ‘First.sh’
$ nano First.sh
Add the following bash script to the file and save the file.
#!/bin/bash
echo "Hello World"
You can run bash file by two ways. One way is by using bash command and another is by
setting execute permission to bash file and run the file. Both ways are shown here.
$ bash First.sh
Or,
$ chmod a+x First.sh
$ ./First.sh
Go to top
Use of echo command:
You can use echo command with various options. Some useful options are mentioned in
the following example. When you use ‘echo’ command without any option then a newline
is added by default. ‘-n’ option is used to print any text without new line and ‘-e’ option is
used to remove backslash characters from the output. Create a new bash file with a
name, ‘echo_example.sh’ and add the following script.
#!/bin/bash
echo "Printing text with newline"
echo -n "Printing text without newline"
echo -e "\nRemoving \t backslash \t characters\n"
Run the file with bash command.
$ bash echo_example.sh
Go to top
Use of comment:
‘#’ symbol is used to add single line comment in bash script. Create a new file named
‘comment_example.sh’ and add the following script with single line comment.
#!/bin/bash
$ bash comment_example.sh
Go to top
Use of Multi-line comment:
You can use multi line comment in bash in various ways. A simple way is shown in the
following example. Create a new bash named, ‘multiline-comment.sh’ and add the
following script. Here, ‘:’ and “ ’ ” symbols are used to add multiline comment in bash
script. This following script will calculate the square of 5.
#!/bin/bash
:'
The following script calculates
the square value of the number, 5.
'
((area=5*5))
echo $area
Run the file with bash command.
$ bash multiline-comment.sh
You can check the following link to know more about the use of bash comment.
https://linuxhint.com/bash_comments/
Go to top
Using While Loop:
Create a bash file with the name, ‘while_example.sh’, to know the use of while loop. In
the example, while loop will iterate for 5 times. The value of count variable will increment
by 1 in each step. When the value of count variable will 5 then the while loop will
terminate.
#!/bin/bash
valid=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 5 ];
then
break
fi
((count++))
done
Run the file with bash command.
$ bash while_example.sh
You can check the following link to know more about the use of while loop.
https://linuxhint.com/bash-while-loop-examples/
Go to top
Using For Loop:
The basic for loop declaration is shown in the following example. Create a file named
‘for_example.sh’ and add the following script using for loop. Here, for loop will iterate
for 10 times and print all values of the variable, counter in single line.
#!/bin/bash
for (( counter=10; counter>0; counter-- ))
do
echo -n "$counter "
done
printf "\n"
Run the file with bash command.
$ bash for_example.sh
You can use for loop for different purposes and ways in your bash script. You can check
the following link to know more about the use of for loop.
https://linuxhint.com/bash-for-loop-examples/
Go to top
Get User Input:
‘read’ command is used to take input from user in bash. Create a file named
‘user_input.sh’ and add the following script for taking input from the user. Here, one
string value will be taken from the user and display the value by combining other string
value.
#!/bin/bash
echo "Enter Your Name"
read name
echo "Welcome $name to LinuxHint"
Run the file with bash command.
$ bash user_input.sh
You can check the following link to know more about the use of user input.
https://linuxhint.com/bash-script-user-input/
Go to top
Using if statement:
You can use if condition with single or multiple conditions. Starting and ending block of
this statement is define by ‘if’ and ‘fi’. Create a file named ‘simple_if.sh’ with the
following script to know the use if statement in bash. Here, 10 is assigned to the
variable, n. if the value of $n is less than 10 then the output will be “It is a one digit
number”, otherwise the output will be “It is a two digit number”. For comparison, ‘-lt’ is
used here. For comparison, you can also use ‘-eq’ for equality, ‘-ne’ for not
equality and ‘-gt’ for greater than in bash script.
#!/bin/bash
n=10
if [ $n -lt 10 ];
then
echo "It is a one digit number"
else
echo "It is a two digit number"
fi
Run the file with bash command.
$ bash simple_if.sh
Go to top
Using if statement with AND logic:
Different types of logical conditions can be used in if statement with two or more
conditions. How you can define multiple conditions in if statement using AND logic is
shown in the following example. ‘&&’ is used to apply AND logic of if statement. Create a
file named ‘if_with_AND.sh’ to check the following code. Here, the value
of username and password variables will be taken from the user and compared with
‘admin’ and ‘secret’. If both values match then the output will be “valid user”, otherwise
the output will be “invalid user”.
!/bin/bash
$ bash if_with_AND.sh
Go to top
Using if statement with OR logic:
‘||’ is used to define OR logic in if condition. Create a file named ‘if_with_OR.sh’ with the
following code to check the use of OR logic of if statement. Here, the value of n will be
taken from the user. If the value is equal to 15 or 45 then the output will be “You won the
game”, otherwise the output will be “You lost the game”.
#!/bin/bash
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
echo "You won the game"
else
echo "You lost the game"
fi
Run the file with bash command.
$ bash if_with_OR.sh
Go to top
Using else if statement:
The use of else if condition is little different in bash than other programming language.
‘elif’ is used to define else if condition in bash. Create a file named, ‘elseif_example.sh’
and add the following script to check how else if is defined in bash script.
#!/bin/bash
if [ $n -eq 101 ];
then
echo "You got 1st prize"
elif [ $n -eq 510 ];
then
echo "You got 2nd prize"
elif [ $n -eq 999 ];
then
echo "You got 3rd prize"
else
echo "Sorry, try for the next time"
fi
Run the file with bash command.
$ bash elseif_example.sh
Go to top
Using Case Statement:
Case statement is used as the alternative of if-elseif-else statement. The starting and
ending block of this statement is defined by ‘case’ and ‘esac’. Create a new file named,
‘case_example.sh’ and add the following script. The output of the following script will be
same to the previous else if example.
#!/bin/bash
$ bash case_example.sh
Go to top
Get Arguments from Command Line:
Bash script can read input from command line argument like other programming
language. For example, $1 and $2 variable are used to read first and second command
line arguments. Create a file named “command_line.sh” and add the following script.
Two argument values read by the following script and prints the total number of arguments
and the argument values as output.
#!/bin/bash
echo "Total arguments : $#"
echo "1st Argument = $1"
echo "2nd argument = $2"
Run the file with bash command.
https://linuxhint.com/command_line_arguments_bash_script/
Go to top
Get arguments from command line with names:
How you can read command line arguments with names is shown in the following script.
Create a file named, ‘command_line_names.sh’ and add the following code. Here, two
arguments, X and Y are read by this script and print the sum of X and Y.
#!/bin/bash
for arg in "$@"
do
index=$(echo $arg | cut -f1 -d=)
val=$(echo $arg | cut -f2 -d=)
case $index in
X) x=$val;;
Y) y=$val;;
*)
esac
done
((result=x+y))
echo "X+Y=$result"
Run the file with bash command and with two command line arguments.
Go to top
Combine String variables:
You can easily combine string variables in bash. Create a file named
“string_combine.sh” and add the following script to check how you can combine string
variables in bash by placing variables together or using ‘+’ operator.
#!/bin/bash
string1="Linux"
string2="Hint"
echo "$string1$string2"
string3=$string1+$string2
string3+=" is a good tutorial blog site"
echo $string3
Run the file with bash command.
$ bash string_combine.sh
Go to top
Get substring of String:
Like other programming language, bash has no built-in function to cut value from any
string data. But you can do the task of substring in another way in bash that is shown in
the following script. To test the script, create a file named ‘substring_example.sh’ with
the following code. Here, the value, 6 indicates the starting point from where the substring
will start and 5 indicates the length of the substring.
#!/bin/bash
Str="Learn Linux from LinuxHint"
subStr=${Str:6:5}
echo $subStr
Run the file with bash command.
$ bash substring_example.sh
Go to top
Add Two Numbers:
You can do the arithmetical operations in bash in different ways. How you can add two
integer numbers in bash using double brackets is shown in the following script. Create a
file named ‘add_numbers.sh’ with the following code. Two integer values will be taken
from the user and printed the result of addition.
#!/bin/bash
echo "Enter first number"
read x
echo "Enter second number"
read y
(( sum=x+y ))
echo "The result of addition=$sum"
Run the file with bash command.
$ bash add_numbers.sh
You can check the following link to know more about bash arithmetic.
https://linuxhint.com/bash_arithmetic_operations/
Go to top
Create Function:
How you can create a simple function and call the function is shown in the following script.
Create a file named ‘function_example.sh’ and add the following code. You can call any
function by name only without using any bracket in bash script.
#!/bin/bash
function F1()
{
echo 'I like bash programming'
}
F1
Run the file with bash command.
$ bash function_example.sh
Go to top
Create function with Parameters:
Bash can’t declare function parameter or arguments at the time of function declaration.
But you can use parameters in function by using other variable. If two values are passed
at the time of function calling then $1 and $2 variable are used for reading the values.
Create a file named ‘function|_parameter.sh’ and add the following code. Here, the
function, ‘Rectangle_Area’ will calculate the area of a rectangle based on the parameter
values.
#!/bin/bash
Rectangle_Area() {
area=$(($1 * $2))
echo "Area is : $area"
}
Rectangle_Area 10 20
Run the file with bash command.
$ bash function_parameter.sh
Go to top
Pass Return Value from Function:
Bash function can pass both numeric and string values. How you can pass a string value
from the function is shown in the following example. Create a file named,
‘function_return.sh’ and add the following code. The function, greeting() returns a string
value into the variable, val which prints later by combining with other string.
#!/bin/bash
function greeting() {
str="Hello, $name"
echo $str
val=$(greeting)
echo "Return value of the function is $val"
Run the file with bash command.
$ bash function_return.sh
You can check the following link to know more about the use of bash function.
https://linuxhint.com/return-string-bash-functions/
Go to top
Make Directory:
Bash uses ‘mkdir’ command to create a new directory. Create a file named
‘make_directory.sh’ and add the following code to take a new directory name from the
user. If the directory name is not exist in the current location then it will create the
directory, otherwise the program will display error.
#!/bin/bash
echo "Enter directory name"
read newdir
`mkdir $newdir`
Run the file with bash command.
$ bash make_directory.sh
Go to top
Make directory by checking existence:
If you want to check the existence of directory in the current location before executing the
‘mkdir’ command then you can use the following code. ‘-d’ option is used to test a
particular directory is exist or not. Create a file named, ‘directory_exist.sh’ and add the
following code to create a directory by checking existence.
#!/bin/bash
echo "Enter directory name"
read ndir
if [ -d "$ndir" ]
then
echo "Directory exist"
else
`mkdir $ndir`
echo "Directory created"
fi
Run the file with bash command.
$ bash directory_exist.sh
You can check the following link to know more about directory creation.
https://linuxhint.com/bash_mkdir_not_existent_path/
Go to top
Read a File:
You can read any file line by line in bash by using loop. Create a file named, ‘read_file.sh’
and add the following code to read an existing file named, ‘book.txt’.
#!/bin/bash
file='book.txt'
while read line; do
echo $line
done < $file
Run the file with bash command.
$ bash read_file.sh
Run the following command to check the original content of ‘book.txt’ file.
$ cat book.txt
You can check the following link to know the different ways to read file.
https://linuxhint.com/read_file_line_by_line_bash/
Go to top
Delete a File:
‘rm’ command is used in bash to remove any file. Create a file named ‘delete_file.sh’ with
the following code to take the filename from the user and remove. Here, ‘-i’ option is used
to get permission from the user before removing the file.
#!/bin/bash
echo "Enter filename to remove"
read fn
rm -i $fn
Run the file with bash command.
$ ls
$ bash delete_file.sh
$ ls
Go to top
Append to File:
New data can be added into any existing file by using ‘>>’ operator in bash. Create a file
named ‘append_file.sh’ and add the following code to add new content at the end of the
file. Here, ‘Learning Laravel 5’ will be added at the of ‘book.txt’ file after executing the
script.
#!/bin/bash
$ bash append_file.sh
Go to top
Test if File Exist:
You can check the existence of file in bash by using ‘-e’ or ‘-f’ option. ‘-f’ option is used in
the following script to test the file existence. Create a file named, ‘file_exist.sh’ and add
the following code. Here, the filename will pass from the command line.
#!/bin/bash
filename=$1
if [ -f "$filename" ]; then
echo "File exists"
else
echo "File does not exist"
fi
Run the following commands to check the existence of the file. Here, book.txt file exists
and book2.txt is not exist in the current location.
$ ls
$ bash file_exist.sh book.txt
$ bash file_exist.sh book2.txt
Go to top
Send Email:
You can send email by using ‘mail’ or ‘sendmail’ command. Before using these
commands, you have to install all necessary packages. Create a file named,
‘mail_example.sh’ and add the following code to send the email.
#!/bin/bash
Recipient=”[email protected]”
Subject=”Greeting”
Message=”Welcome to our site”
`mail -s $Subject $Recipient <<< $Message`
Run the file with bash command.
$ bash mail_example.sh
Go to top
Get Parse Current Date:
You can get the current system date and time value using `date` command. Every part of
date and time value can be parsed using ‘Y’, ‘m’, ‘d’, ‘H’, ‘M’ and ‘S’. Create a new file
named ‘date_parse.sh’ and add the following code to separate day, month, year, hour,
minute and second values.
#!/bin/bash
Year=`date +%Y`
Month=`date +%m`
Day=`date +%d`
Hour=`date +%H`
Minute=`date +%M`
Second=`date +%S`
echo `date`
echo "Current Date is: $Day-$Month-$Year"
echo "Current Time is: $Hour:$Minute:$Second"
Run the file with bash command.
$ bash date_parse.sh
Go to top
Wait Command:
wait is a built-in command of Linux that waits for completing any running
process. wait command is used with a particular process id or job id. If no process id or
job id is given with wait command then it will wait for all current child processes to
complete and returns exit status. Create a file named ‘wait_example.sh’ and add the
following script.
#!/bin/bash
echo "Wait command" &
process_id=$!
wait $process_id
echo "Exited with status $?"
Run the file with bash command.
$ bash wait_example.sh
You can check the following link to know more about wait command.
Sleep Command:
When you want to pause the execution of any command for specific period of time then
you can use sleep command. You can set the delay amount by seconds (s), minutes
(m), hours (h) and days (d). Create a file named ‘sleep_example.sh’ and add the
following script. This script will wait for 5 seconds after running.
#!/bin/bash
$ bash sleep_example.sh
You can check the following link to know more about sleep command.
#simple intrest
str1="linux";
echo "enter second string";
read str2;
if [ $str1 = $str2 ]
echo " same string "
;
if [ $str1 != $str2 ]
echo " not same string ";
fi
fi
#Output
#Output
#Output
enter a character
a
you enter vowel
#Output
enter a character
S
you enter upper case letter
#while loop
Num=1
B=1
echo “ which table you want to print ?”
read which_table
echo “tillwhat value you want to print==>”
read a
echo “tavle-->”
while [ $num – le $a ]
do
b= `expr $num \ * $which _ table`
echo “$b \n”
num=`expr $num +1`
done
#Output
which table you want to print ?
64
128
192
256
320
384
448
512
576
640
#Output
enter a string
979
it is palindrom
#addition multiplication devision
#Output
enter a
2
enter b
2
enter c
2
enter d
2
4
a=10;
b=20;
echo "`expr $a + $b`";
echo "`expr $a - $b`";
echo "`expr $a \* $b`";
echo "`expr $a / $b`";
#Output
30
-10
200
0.5
#New file mane
#Output
declare -a a;
a[0]=0;
a[1]=1;
echo “ ${a[*]} ”;
#Output
“o1”
#Declare a -a
declare -a a;
echo "enter no of elements";
read n;
for((i=0;i<n;i++))
do
read a[$i]};
done
echo "the array is:";
for((i=0;i<n;i++))
do
echo “ ${a[$i]}”;
#Output
enter no of elements
the array is:
line 6: read: `a[0]}'
line 6: read: `a[1]}'
line 6: read: `a[2]}'
line 6: read: `a[3]}'
line 6: read: `a[4]}'
line 6: read: `a[5]}'