Monday, December 27, 2010

How to copy file permissions from one file to another


Introduction

You may know how to change file permissions using chmod but, if you already have a file with the permissions you want to assign to some other files, you can use --reference option in chmod

How to copy or replicate file permissions, using another file as reference

If you want to use a file as reference to copy its permissions to other files you can do that using this command
chmod --reference  
As an example, if you have this:
-rwxrwxrwx 1 ggarron ggarron 0 Dec 20 15:35 1.txt
-rwx------ 1 ggarron ggarron 0 Dec 20 15:35 2.txt
And you run:
chmod --reference 1.txt 2.txt
You should then have this:
-rwxrwxrwx 1 ggarron ggarron 0 Dec 20 15:35 1.txt
-rwxrwxrwx 1 ggarron ggarron 0 Dec 20 15:35 2.txt
Just be sure, you are the owner of the files, you that you have permission to change them.

CD - Command Tips


Introduction

cd may be one of the most used Linux commands. From Wikipedia:
cd, sometimes also available as chdir (change directory), is a command line command to change the current working directory in operating systems such as Unix, DOS, OS/2, AmigaOS (where if a bare path is given, cd is implied), Windows, and Linux. It is also available for use in shell scripts and batch files.
There are some few tips that can help you save some time, while navigating between your folders in Linux. This article will touch a few of them, if you know more, please share in the comments.

Change directory cd command tips for Linux

Return to home
I wish in real life could be that easy to go back home as it is in Linux, and maybe baseball players may wish the same in the diamond field.
Well, to go back home, no matter where in the directory tree you might be just enter at the command prompt:
cd
That's it, with no parameters, you will be taken home.
One level below
If you want to go back just one level, enter at the Linux command prompt:
cd ..
There is a space between cd and .. (the two points).
Two levels below
If you want to go back two levels, enter:
cd ../..
Now you have the idea, and for sure you know how to go back three, four, five... and more levels below the current directory.
To a folder in a parallel level
If you want to go to a folder in the parallel level, where you actually are, you do not need to go down and then up again, you can do it in just one step.
Let's see this example, suppose you are:
pwd
/var/log/cups
Now, if you enter:
cd ../samba/
You will be at:
pwd
/var/log/samba
Jump between folders
If you want to jump between folders, just like you jump between T.V. Channels with the remote control, with the "recall" or "jump" key, use:
cd -
Note the space between cd and the dash -
This way you can go back and forth, between two directories, this is very useful when are working on two folders at the same time. I use it a lot, when editing a shell script in my home directory, and testing the script in /tmp/ folder

Tuesday, December 21, 2010

Linux Changing Run Levels


Recently I was taking class for Linux sys admin course. Some one asked me "How do changing run levels affect us or our users?" I replied with following answer:
Well if you are moving to higher run levels, you may make additional services available to users, while moving to a lower run level will causes to services (daemons) to become unavailable. On production server run level 3 is the normally used and rarely changed. However some administrative tasks require the administrator to move system to run level 1 i.e single user mode.
Use the init command to change rune levels:
# init 1
Runlevel and usage:
  • Runlevel 0 is halt
  • Runlevel 1 is single-user
  • Runlevels 2-5 are multi-user (some distro uses RUN level 5 to start X [KDE/Gnome])
  • Runlevel 6 is for rebooting system
Typing init 3 will move system to run level 3:
# init 3
On most Linux server system default run level is 3 and on most Linux Desktop system default run level is 5. The default run level is defined by the initdefault line at the top of /etc/inittab. So if you wanna change default run level open file /etc/inittab and edit entry initdefault:
# vi /etc/inittab
Set initdefault to 5, so that you can boot to X next time when Linux comes up:
id:5:initdefault:
Save file and reboot to see changes.
getty is the program which opens a tty port, prompts for a login name and password (via /bin/login command). Your console displays a login/password prompt at run levels 1 through 6. You can use ALT+F1...ALT+F6 keys to switch console (use CTRL+ALT+F1..F6 under X windows).
However my experience so far is that students get confused with ssh and KDE/Gnome Desktop login.
SSH logins are handled by sshd server which starts at run level 2/3. KDE/Genome Desktop login are handled by GDM/XDM/KDM display manager which starts at run level 5 (however Debian Linux and some other distro can start them from run level 2 via special rc.d script located in /etc/init.d/gdm)

Tuesday, December 14, 2010

Linux crontab, cronjob Syntax, How to and tips

Cron is a time-based job scheduler in Unix-like computer operating systems. The name cron comes from the word “chronos”, Greek for “time”.[1] Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration, though its general-purpose nature means that it can be used for other purposes, such as connecting to the Internet and downloading email
Cron is driven by a crontab (cron table) file, a configuration file that specifies shell commands to run periodically on a given schedule. The crontab files are stored where the lists of jobs and other instructions to the cron daemon are kept. Users can have their own individual crontab files and often there is a system wide crontab file (usually in /etc or a subdirectory of /etc) which only system administrators can edit.
So, as you can see, cron is really useful to perform repetitive tasks in a Linux machine, or to run some specific task in a given hour and day only one time.
In other words is a scheduler of jobs for Linux.

Editing Crontab

Log in as the user you want to edit his / her crontab and run:
crontab -e
To list his cronjobs
crontab -l
If you have access to root account you may edit anyone’s files.
crontab -u [user] -e

Changing the default Linux editor program

By default the editor for crontab is vi, but you can change it, just run:
export EDITOR=/usr/bin/nano
Now, if you run
crontab -e
you will be editing the file using nano

Tips and example for Crontab

Syntax
MIN HOUR DOM MON DOW CMD
Where
  • MIN = Minute 0-59
  • HOUR = Hour 0-23
  • DOM = Day of month 1-31
  • MON = Month 1-12
  • DOW = Day of week 0-6 Where 0=Sunday
  • CMD = Command, the command that is going to run in a given moment.
You may want to check also the differences in crontab syntax depending the version you are using or the Linux distribution you are working with.
Schedule a task for an specific moment one time run
12 02 2 11 * /home/user/my-task.pl
So, at 2:12 am on November the 2nd the program /home/user/my-task.pl will run.
Run a command twice in a day, month, or any other time frame
You can use commas to tell the Operating System you want to run the program twice. Let’s suppose in the above example, you want to run on November and December the same program.
12 02 02 11,12 * /home/user/my-task.pl
Run a command in time intervals, like weekdays
00 14 * * 1-5 /home/user/my-task.pl
What about only on weekends and in the morning
06-12 * * 6,7 /home/user/my-task.pl
Run once every year, month, day
You can use these special words for this:
  • @yearly -Every year January first 00:00
  • @daily -Every day at 00:00
  • @hourly -Every hour at 0 minutes
  • @reboot -As soon as you reboot your computer
Run a program every X minutes
Let’s say you want to run a command every 15 minutes, enter this line the crontab file:
*/15 * * * * command

Saturday, December 4, 2010

Shell Script Examples (Problem & Solution)

ARRAY in Shell Script


#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}

# echo each element in array
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
    echo ${ARRAY[${i}]}
done

Shell Script Examples (Problem & Solution)

Perform Arithmetic Operation 



#!/bin/bash

echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ]
# and $(( expression #)) its your choice which you use

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A
result=16#E6A
echo $result

Shell Script Examples (Problem & Solution)

Problem : How to write shell script that will add two nos, which are supplied as command line argument, and if this two nos are not given show error and its usage.

Solution :


if [ $# -ne 2 ]
then
echo "Usage - $0 x y"
echo " Where x and y are two nos for which I will print sum"
exit 1
fi
echo "Sum of $1 and $2 is `expr $1 + $2`"
Pro Bash Programming: Scripting the GNU/Linux Shell (Expert's Voice in Linux)
--------------------------------------------------------------------------------------------------------


Problem : Write Script to find out biggest number from given three nos. Nos are supplies as command line argument. Print error if sufficient arguments are not supplied.

Solution : 

#
# Algo:
# 1) START: Take three nos as n1,n2,n3.
# 2) Is n1 is greater than n2 and n3, if yes
# print n1 is bigest no goto step 5, otherwise goto next step
# 3) Is n2 is greater than n1 and n3, if yes
# print n2 is bigest no goto step 5, otherwise goto next step
# 4) Is n3 is greater than n1 and n2, if yes
# print n3 is bigest no goto step 5, otherwise goto next step
# 5) END
#
#

if [ $# -ne 3 ]
then
echo "$0: number1 number2 number3 are not given" >&2
exit 1
fi
n1=$1
n2=$2
n3=$3
if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ]
then
echo "$n1 is Bigest number"
elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ]
then
echo "$n2 is Bigest number"
elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ]
then
echo "$n3 is Bigest number"
elif [ $1 -eq $2 ] && [ $1 -eq $3 ] && [ $2 -eq $3 ]
then
echo "All the three numbers are equal"
else
echo "I can not figure out which number is biger"
fi
Pro Bash Programming: Scripting the GNU/Linux Shell
------------------------------------------------------------------------------------------------------------
Problem : Write script to print nos as 5,4,3,2,1 using while loop.


Solution : 

# Algo:
# 1) START: set value of i to 5 (since we want to start from 5, if you
# want to start from other value put that value)
# 2) Start While Loop
# 3) Chechk, Is value of i is zero, If yes goto step 5 else
# continue with next step
# 4) print i, decement i by 1 (i.e. i=i-1 to goto zero) and
# goto step 3
# 5) END
#
i=5
while test $i != 0
do
echo "$i
"
i=`expr $i - 1`
done
Linux Command Line and Shell Scripting Bible
-------------------------------------------------------------------------------------------------------------
Problem : Write Script, using case statement to perform basic math operation as
follows
+ addition
- subtraction
x multiplication
/ division
The name of script must be 'q4' which works as follows
$ ./q4 20 / 3, Also check for sufficient command line arguments

Solution : 

if test $# = 3
then
case $2 in
+) let z=$1+$3;;
-) let z=$1-$3;;
/) let z=$1/$3;;
x|X) let z=$1*$3;;
*) echo Warning - $2 invalied operator, only +,-,x,/ operator allowed
exit;;
esac
echo Answer is $z
else
echo "Usage - $0 value1 operator value2"
echo " Where, value1 and value2 are numeric values"
echo " operator can be +,-,/,x (For Multiplication)"
fi
Write Script to see current date, time, username, and current directory.
echo "Hello, $LOGNAME"
echo "Current date is `date`"
echo "User is `who i am`"
echo "Current direcotry `pwd`"
Linux Command Line and Shell Scripting Bible
-------------------------------------------------------------------------------------------------------------
Problem : Write script to print given number in reverse order, for eg. If no is 123 it must print as 321.


Solution : 


# Algo:
# 1) Input number n
# 2) Set rev=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct revrse no as rev * 10 + sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print rev
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find reverse of given number"
echo " For eg. $0 123, I will print 321"
exit 1
fi

n=$1
rev=0
sd=0

while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10 + $sd`
n=`expr $n / 10`
done
echo "Reverse number is $rev"
Classic Shell Scripting
-------------------------------------------------------------------------------------------------------------
Problem : Write script to print given numbers sum of all digit, For eg. If no is 123 it's sum of all digit will be 1+2+3 = 6.


Solution :


# Algo:
# 1) Input number n
# 2) Set sum=0, sd=0
# 3) Find single digit in sd as n % 10 it will give (left most digit)
# 4) Construct sum no as sum=sum+sd
# 5) Decrment n by 1
# 6) Is n is greater than zero, if yes goto step 3, otherwise next step
# 7) Print sum
#
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
echo " I will find sum of all digit for given number"
echo " For eg. $0 123, I will print 6 as sum of all digit (1+2+3)"
exit 1
fi

n=$1
sum=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
sum=`expr $sum + $sd`
n=`expr $n / 10`
done
echo "Sum of digit for numner is $sum"
Mastering Unix Shell Scripting: Bash, Bourne, and Korn Shell Scripting for Programmers, System Administrators, and UNIX Gurus
-------------------------------------------------------------------------------------------------------------
Problem : How to perform real number calculation in shell script and store result to
third variable , lets say a=5.66, b=8.67, c=a+b?

Solution :


a=5.66
b=8.67
c=`echo $a + $b | bc`
echo "$a + $b = $c"
-------------------------------------------------------------------------------------------------------------
Problem : Write script to determine whether given file exist or not, file name is supplied as command line argument, also check for sufficient number of command line argument.


Solution : 


if [ $# -ne 1 ]
then
echo "Usage - $0 file-name"
exit 1
fi

if [ -f $1 ]
then
echo "$1 file exist"
else
echo "Sorry, $1 file does not exist"
fi
Learning the bash Shell: Unix Shell Programming (In a Nutshell (O'Reilly))
-------------------------------------------------------------------------------------------------------------
Problem : Write script to print contains of file from given line number to next given number of lines. For e.g. If we called this script as Q13 and run as
$ Q13 5 5 myf , Here print contains of 'myf' file from line number 5 to next 5 line of that file.


Solution : 

if [ $# -eq 0 ]
then
echo "$0:Error command arguments missing!"
echo "Usage: $0 start_line uptoline filename"
echo "Where start_line is line number from which you would like to print file"
echo "uptoline is line number upto which would like to print"
echo "For eg. $0 5 5 myfile"
echo "Here from myfile total 5 lines printed starting from line no. 5 to"
echo "line no 10."
exit 1
fi

#
# Look for sufficent arg's
#

if [ $# -eq 3 ]; then
if [ -e $3 ]; then
tail +$1 $3 | head -n$2
else
echo "$0: Error opening file $3"
exit 2
fi
else
echo "Missing arguments!"
fi
Linux Shell Scripting with Bash
-------------------------------------------------------------------------------------------------------------
Problem : Write script called sayHello, put this script into your startup file called .bash_profile, the script should run as soon as you logon to system, and it print any one of the following message in infobox using dialog utility, if installed in your system, If dialog utility is not installed then use echo statement to print message : -
Good Morning
Good Afternoon
Good Evening , according to system time.


Solution : 


temph=`date | cut -c12-13`
dat=`date +"%A %d in %B of %Y (%r)"`

if [ $temph -lt 12 ]
then
mess="Good Morning $LOGNAME, Have nice day!"
fi

if [ $temph -gt 12 -a $temph -le 16 ]
then
mess="Good Afternoon $LOGNAME"
fi

if [ $temph -gt 16 -a $temph -le 18 ]
then
mess="Good Evening $LOGNAME"
fi

if which dialog > /dev/null
then
dialog --backtitle "Linux Shell Script Tutorial"\
--title "(-: Welcome to Linux :-)"\
--infobox "\n$mess\nThis is $dat" 6 60
echo -n " Press a key to continue. . . "
read
clear
else
echo -e "$mess\nThis is $dat"
fi
Practical Guide to Linux Commands, Editors, and Shell Programming, A (2nd Edition)
-------------------------------------------------------------------------------------------------------------
Problem : How to write script, that will print, Message "Hello World" , in Bold and Blink effect, and in different colors like red, brown etc using echo command.

Solution : 


# Syntax: echo -e "escape-code your message, var1, var2 etc"
# For eg. echo -e "\033[1m Hello World"
#                               |                  |
#                               |                  |
#                       Escape code    Message
#

clear
echo -e "\033[1m Hello World"
# bold effect
echo -e "\033[5m Blink"
# blink effect
echo -e "\033[0m Hello World"
# back to noraml

echo -e "\033[31m Hello World"
# Red color
echo -e "\033[32m Hello World"
# Green color
echo -e "\033[33m Hello World"
# See remaing on screen
echo -e "\033[34m Hello World"
echo -e "\033[35m Hello World"
echo -e "\033[36m Hello World"

echo -e -n "\033[0m "
# back to noraml

echo -e "\033[41m Hello World"
echo -e "\033[42m Hello World"
echo -e "\033[43m Hello World"
echo -e "\033[44m Hello World"
echo -e "\033[45m Hello World"
echo -e "\033[46m Hello World"


echo -e "\033[0m Hello World"
# back to noraml
Classic Shell Scripting
-------------------------------------------------------------------------------------------------------------
Problem : Write script to implement background process that will continually print current time in upper right corner of the screen , while user can do his/her normal job at $ prompt.

Solution : 

echo
echo "Digital Clock for Linux"
echo "To stop this clock use command kill pid, see above for pid"
echo "Press a key to continue. . ."

while :
do
ti=`date +"%r"`
echo -e -n "\033[7s" #save current screen postion & attributes
#
# Show the clock
#

tput cup 0 69 # row 0 and column 69 is used to show clock

echo -n $ti # put clock on screen

echo -e -n "\033[8u" #restore current screen postion & attributs
#
#Delay fro 1 second
#
sleep 1
done

Thursday, December 2, 2010

Database in Linux

Follow the instruction to create database and tabel in mysql.

Go to terminal with root.
Assuming you have installed mysql in your linux version and no password for accessing mysql.
#mysql -u root
mysql> create database new;
Query OK, 1 row effected (0.02 Sec)
mysql> use new;
database changed
mysql>create table emp_data(EMP_NO varchar(10),EMP_NAME varchar(30),EMP_ADDRESS varchar(60),EMP_AGE varchar(3),EMP_GENDER varchar(6),EMP_DESIGNATION varchar(15),EMP_BASIC_SALARYvarchar(10));

TABLE CREATED SUCCESSFULLY.