Wednesday, January 24, 2018

Unix/Linux Commands 2

3. File Permissions

Description:

Every user on a Unix system has a unique username, and is a member of at least one group (the primary group for that user). This group information is held in the password file (/etc/passwd). A user can also be a member of one or more other groups. The auxiliary group information is held in the file /etc/group. Only the administrator can create new groups or add/delete group members (one of the shortcomings of the system).

Every directory and file on the system has an owner, and also an associated group. It also has a set of permission flags which specify separate read, write and execute permissions for the ‘user’ (owner), ‘group’, and ‘other’ (everyone else with an account on the computer).The ‘ls’ command shows the permissions and group associated with files when used with –l option. On some systems (e.g. Coos), the ‘-g’ option is also needed to see the group information.

read permissions to user (owner)
|write permissions to user (owner)
||execution permissions to user (owner)
||| read permissions to all others
||| |write permissions to all others
||| ||execution permissions to all others
||| |||
-rw-r--r—
| |||
| ||execution permissions to group
file/directory |write permissions to group
read permissions to group

File Access Permissions:

0 or –
4 or r
2 or w
1 or x

User Group Codes:

u – User
g – Group
o – Other

Example:

drwx------ 2 richard staff 2048 Jan 2 1997 private
drwxrws--- 2 richard staff 2048 Jan 2 1997 admin
-rw-rw---- 2 richard staff 12040 Aug 20 1996 admin/userinfo
drwxr-xr-x 3 richard user 2048 May 13 09:27 public

The chmod command

Description:
The chmod command changes the permissions of each given file according to mode, which can be either a symbolic representation of changes to make, or an octal number representing the bit pattern for the new permissions.

Synopsis:

chmod [OPTION]… MODE[,MODE]… FILE…
chmod [OPTION]… OCTAL-MODE FILE…
chmod [OPTION]… --reference=RFILE FILE…

Example:

• chmod g+r myFile #Giving read permission to group
• chmod ugo+rwx myFile #Giving read, write and execute permissions to user, group and others.

Scenario:

• change the access privileges on the files.

The umask command

Description:

The umask (UNIX shorthand for “user file-creation mode mask”) is a four-digit octal number that UNIX uses to determine the file permission for newly created files. Every process has its own umask, inherited from its parent process.
The umask specifies the permissions you do not want given by default to newly created files and directories.

Synopsis:

• umask CODE

Example:

• umask 0022

Scenario:

• Change the default permissions for the newly created file or folder.

The chown command

Description:

The chown command changes the user and/or group ownership of each given file, according to its first non-option argument, which is interpreted as follows. If only a user name (or numeric user ID) is given, that user is made the owner of each given file, and the files group is not changed. If the user name is followed by a colon or dot and a group name (or numeric group ID), with no spaces between them, the group ownership of the files is changed as well. If a owner of the files and the group of the files is changed to that user’s login group. If the colon or dot and group are given, but the user name is omitted, only the group of the files is changed; in this case, chown performs the same function as chgrp.

Synopsis:

chown [OPTION]… OWNER[:[GROUP]] FILE…
chown [OPTION]… GROUP FILE…
chown [OPTION]… --reference=RFILE FILE…

Example:

• chown ramu file.txt #Given permissions as owner to user ramu.

Scenario:

• Change the ownership of the file.

The chgrp command

Description:

The chgrp command changes the group ownership of the file.

Synopsis:

chgrp [OPTION]… GROUP FILE…
chgrp [OPTION]… --reference=RFILE FILE…

Example:

• chgrp hope file.txt #Would change the group to hope for the file file.txt if present and the group hope is valid.

Scenario:

• Change the group ownership of the file.

4. Environment variables

Global variables

Description:

When user login, there will be a large number of global System variables that are already defined. These can be freely referenced and used in your shell scripts.

However, care is needed when you change the values of some of these variables, such as the PATH variables.

Local variables

Description:

Within a shell script, you can create as many new variables as needed. Any variable created in the manner remains in existence only within that shell ‘i.e. is local to that shell’.

When the shell execution finishes and the control returns back to the invoking level these variables are automatically destroye

5. The Boolean Operators

Description:

There are the operators to check more than one condition.

Synopsis:

Condition condition

Operators:

-a AND
-o OR
! NOT

6. The Logical Operators

Description:

There are the operators to compare the string and integer values.

Synopsis:

Operand operand

Operators:

-gt Greater than
-ge Greater than or equal to
-lt Less than
-le Less than or equal to
-eq Equal to
-ne Not equal to
> Greater than
>= Greater than or equal to
< Less than <= Less than or equal to = Equal to < > Not equal to
!= Not equal to


7. Redirecting the Output

Description:

Use the > symbol to redirect the output of a command. To append use the >> symbol in place of >.

Synopsis:

command > file

Example:

Cat > list1 #Type some text after Return. Press Ctrl + D after entering the text.

8. Pipes

Description:

Redirecting the output of one command as input to the other command.

Synopsis:

command1 | command2

Example:

• Check whether the use kk is logged in or not.

Who | grep ramu #this command return the details if the user ramu logged in.

7. Redirecting the Output

Description:

Use the > symbol to redirect the output of a command. To append use the >> symbol in place of >.

Synopsis:

command > file

Example:

Cat > list1 #Type some text after Return. Press Ctrl + D after entering the text.

8. Pipes

Description:

Redirecting the output of one command as input to the other command.

Synopsis:

command1 | command2

Example:

• Check whether the use kk is logged in or not.

Who | grep ramu #this command return the details if the user ramu logged in.

9. Conditional Statements

if statement

Description:

The “if” statement tests if the condition is true (exit status is 0, success). If it is the “then” part gets executed.

Most of the time a very special command called test is used inside if-statements. It can be used to compare strings or test if a file exists, is readable etc…

The “test” command is written as square brackets “ [ ] “. Note that space is significant here: Make sure that you always have space around the brackets.

Examples:

[ -f “somefile” ] : Test if somefile is a file.
[ -X “/bin/ls” ] : Test if /bin/ls exists and is executable.
[ -n “$var” ] : Test if the variable $var contains something
[ “$a” = “$b” ] : Test if the variables “$a” and “$b” are equal

Run the command “man test” and you get a long list of all kinds of test operators for comparisons and files.

Synopsis:

if ….; then
….
elif ….; then
….
else
….
fi

Example 1:

Using this in a shell script is straight forward:

#!/bin/bash
if [ “$SHELL” = “/bin/bash” ]; then
echo “your login shell is the bash (bourne again shell)”
else
echo “your login shell is not bash but $SHELL
fi

Example 2:

Example to copy file from source to target using if statement:

#!/bin/bash
echo “Enter source filename and target filename”
read src trg
if cp $src $trg
then
echo file copied successfully
else
echo failed to copy the file
fi

Example 3:

Example to search for a pattern in given file using if statement:

#!/bin/bash
echo “Enter a file name”
read fname
echo “Enter string to search”
read str
if grep $str $fname
then
echo “$str is found in $fname”
else
echo “$str I not found in $fname”
fi

Example 4:

#!/bin/bash
if test $# -eq 0
then
echo There must be at least one parameter on the command line
exit 1
fi

Example 5:

Example to see nested if statement:

#!/bin/bash
if [ $1 -gt 0 ]; then
echo “$1 is positive number”
elif [ $1 –lt 0 ]
then
echo “$1 is negative number”
elif [ $1 -eq 0 ]
then
echo “$1 is zero”
else
echo “Opps! $1 is not number, give number”
fi

case statement

Description:

The case statement can be used to match (using shell wildcards such as * and ?) a given string against a number of possibilities.

Synopsis:

case … in
…) do something here;
esac

Example:

#!/bin/bash
case $# in
0) echo no parameters;;
1) echo only one parameter.
echo put commands to be executed here.;;
*) echo more than one parameter.
echo enter code here.;;
esac
exit0

for loop statement

Description:

Looping over a set of filenames is very common, and the Shell’s for construct is the only Shell control flow statement that is commonly typed at the prompt rather than putting it in a script file.

Synopsis:

for in
do
commands ;
commands ;
done

Example 1:

• A for loop construct to display filenames one file per line

for i in *
do
echo $i;
done

Example 2:

• A for loop construct to display numbers

#! /bin/bash
for i in *
do
for i in 1 2 3 4 5 6 7 8 9 0
do
echo $i
done

Example 3:

• To test command line arguments using for loop

#! /bin/bash
# using for loop
if [ $# -eq 0 ]
then
echo “Error – Number missing from command line argument”
echo “Syntax : $0 number”
echo “Use to print multiplication table for given number”
exit 1
fi

n=$1
for l in 1 2 3 4 5 6 7 8 9 10
do
echo “$n * $i = ‘expr $i \* $n
done

Example 4:

• To print the numbers from 0 to 5 using for loop

#! /bin/bash
#using for loop
For (( i=0; I <= 5; i++ )) do echo $i done while loop statement

Description:

This loop users the exit status from a command to controls the execution of the commands(s) in the body of the loop. The loop is executed returns a non-zero status.

Synopsis:

While command
do
commands ;
commands ;
done

Example 1:

• Printing the numbers from 1 to 10

#!/bin/bash
# using while loop
echo “The numbers from 1 to 10 are:”
i=1
while [ $1 -le 10 ]
do
echo $i
i= ‘expr $i + 1’
done

Example 2:

• Printing the first 10 positive numbers using the while loop.

#!/bin/bash
# using while loop
num=l # assign a value 1 to a variable num
while [ $num -le 10 ]
do
echo $num
num= ‘expr $num + ‘ # increment num by 1
done

Example 3:

• To test command line arguments using while statement.

#!/bin/bash
# using while loop
if [ $# -eq 0 ]
then
echo “Error - Number missing from command line argument”
echo “Syntax : $0 number”
echo “Use to print multiplication table for given number”
exit 1
fi
n=$1
i=1
while [ $i -le 10 ]
do
echo “$n * $i = ‘expr $i \*$n’
i= ‘expr $i +1’
done

until loop statement

Description:

This loop checks the exit status of the command, and executes the command(s) enclosed within the do and done statement, until the condition command returns a true (a zero status).

Synopsis:

until condition
do
commands ;
commands ;
done

Example:

• Printing the first 10 positive numbers using until loop.

num=1
until [ $num -gt 0 ]
do
echo $num
num= ‘expr $num+1’
done

10. The continue and break in loops

Description:

Sometimes, we require skipping the remaining commands of a loop and returning to the beginning of the loop. Alternatively, the need may arise to terminate and exit the loop. The shell provides the commands break and continue for these purposes.

Synopsis:

continue # to return control to the beginning of a loop
break # to exit a loop

Example:

#Script
ans=”Y”

while [ do $ans =”Y” -o $ans = “y” ]
do
echo “Enter the name:\c”
read name
if [ -z “$name” ]
then
echo “Name cannot be blank”
continue
fi
echo “Enter the grade:\c”
read grade
echo “Enter basic:\c”
read basic
if [ $basic -lt 0 ]
then
exit
fi
echo $name:$grade:$basic
echo “Want to continue:\c”
read ans
done

11. Parameters to shell scripts

Description:

Parameters can also be passed to a shell script in a similar manner to the UNIX commands. This is advantageous in two ways – shell scripts are made more generic and they get executed faster by not having to wait for user input.

Parameters:

Parameter count : $#
All parameters : $*
The command parameters : $0
Positional parameters : $1,$2 …… $n
Listing shell variables : set

Example:

• Write a shell script disp_sum, which will accept 5 numbers as parameters and display their sum. Also display the contents of the different variables in the script.

#Script to accept 5 numbers and display their sum
echo “The parameters passed are: $1, $2, $3, $4, $5”
echo “The name of script is : $0”
echo “The number of parameters passed are: $#”
sum= ‘expr $1+ $2 + $3 + $4 + $5’ #calculate the sum
echo “The sum is $sum”

12. Functions

Description:

As soon as you have a more complex program you will find that you use the same code in several places and also find it helpful to give it some structure.

Synopsis:

Functionname ()
{
# inside the body $1 is the first argument given to the function
# $2 the second …
body
}

Example:

• Write a function to concentrate 2 strings.

f_contact()
# Arg_1 = str1
# Arg_2 = str2
{
echo “$1 $2”
}

Environment Variables
env:

SHELL=/bin/bash
TERM=ansi
HISTSIZE=1000
USER=andy
MAIL=/var/spool/mail/andy
PATH=/usr/Kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/andy/bin
INPUTRC=/etc/inputrc
PWD=/home/andy
LANG=en_US.UTF-8
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SHLVL=1
HOME=/home/andy
LOGNAME=andy
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
_=/bin/env

set:

BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]=”3” [1]=”00” [2]=”16” [3]=”1” [4]=”release” [5]=”i386-redhat-linux-gnu”)
BASH_VERSION=’3.00.16(1)-release’
COLORS=/etc/DIR_COLORS
COLUMNS=128
DIRSTACK=()
EUID=525
GROUPS=()
G_BROKEN_FILENAMES=1
HISTFILE=/home/andy/.bash_history
HISTFILESIZE=1000
HISTSIZE=1000
HOME=/home/andy
HOSTNAME=fedora
HOSTTYPE=i386
IFS=$’ \t\n’
INPUTRC=/etc/inputrc
LANG=en_US.UTF-8
LESSOPEN=’|/usr/bin/lesspipe.sh %s’
LINES=60
LOGNAME=andy
MACHTYPE=i386-redhat-linux-gnu
MAIL=/var/spool/mail/andy
MAILCHECK=60
OPTERR=1
OPTIND=1
OSTYPE=linux-gnu
PATH=/usr/Kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/andy/bin
PIPESTATUS=([0]=”0”)
PPID=8094
PS1=’[\u@\h \w]\$’
PS2=’>’
PS4=’+’
PWD=/home/andy
REMOTEHOST=100.50.25.62
SHELL=/bin/bash
SHLVL=1
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SUPPORTED=en_US.UTF-8:en_US:en
TERM=ansi
UID=525



Thanks for reading.
If you like this post please follow us for more updates about technology related updates.

No comments: