Unix / Linux – Quick Guide ”; Previous Next Unix – Getting Started What is Unix ? The Unix operating system is a set of programs that act as a link between the computer and the user. The computer programs that allocate the system resources and coordinate all the details of the computer”s internals is called the operating system or the kernel. Users communicate with the kernel through a program known as the shell. The shell is a command line interpreter; it translates commands entered by the user and converts them into a language that is understood by the kernel. Unix was originally developed in 1969 by a group of AT&T employees Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna at Bell Labs. There are various Unix variants available in the market. Solaris Unix, AIX, HP Unix and BSD are a few examples. Linux is also a flavor of Unix which is freely available. Several people can use a Unix computer at the same time; hence Unix is called a multiuser system. A user can also run multiple programs at the same time; hence Unix is a multitasking environment. Unix Architecture Here is a basic block diagram of a Unix system − The main concept that unites all the versions of Unix is the following four basics − Kernel − The kernel is the heart of the operating system. It interacts with the hardware and most of the tasks like memory management, task scheduling and file management. Shell − The shell is the utility that processes your requests. When you type in a command at your terminal, the shell interprets the command and calls the program that you want. The shell uses standard syntax for all commands. C Shell, Bourne Shell and Korn Shell are the most famous shells which are available with most of the Unix variants. Commands and Utilities − There are various commands and utilities which you can make use of in your day to day activities. cp, mv, cat and grep, etc. are few examples of commands and utilities. There are over 250 standard commands plus numerous others provided through 3rd party software. All the commands come along with various options. Files and Directories − All the data of Unix is organized into files. All files are then organized into directories. These directories are further organized into a tree-like structure called the filesystem. System Bootup If you have a computer which has the Unix operating system installed in it, then you simply need to turn on the system to make it live. As soon as you turn on the system, it starts booting up and finally it prompts you to log into the system, which is an activity to log into the system and use it for your day-to-day activities. Login Unix When you first connect to a Unix system, you usually see a prompt such as the following − login: To log in Have your userid (user identification) and password ready. Contact your system administrator if you don”t have these yet. Type your userid at the login prompt, then press ENTER. Your userid is case-sensitive, so be sure you type it exactly as your system administrator has instructed. Type your password at the password prompt, then press ENTER. Your password is also case-sensitive. If you provide the correct userid and password, then you will be allowed to enter into the system. Read the information and messages that comes up on the screen, which is as follows. login : amrood amrood”s password: Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73 $ You will be provided with a command prompt (sometime called the $ prompt ) where you type all your commands. For example, to check calendar, you need to type the cal command as follows − $ cal June 2009 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 $ Change Password All Unix systems require passwords to help ensure that your files and data remain your own and that the system itself is secure from hackers and crackers. Following are the steps to change your password − Step 1 − To start, type password at the command prompt as shown below. Step 2 − Enter your old password, the one you”re currently using. Step 3 − Type in your new password. Always keep your password complex enough so that nobody can guess it. But make sure, you remember it. Step 4 − You must verify the password by typing it again. $ passwd Changing password for amrood (current) Unix password:****** New UNIX password:******* Retype new UNIX password:******* passwd: all authentication tokens updated successfully $ Note − We have added asterisk (*) here just to show the location where you need to enter the current and new passwords otherwise at your system. It does not show you any character when you type. Listing Directories and Files All data in Unix is organized into files. All files are organized into directories. These directories are organized into a tree-like structure called the filesystem. You can use the ls command to list out all the files or directories available in a directory. Following is the example of using ls command with -l option. $ ls -l total 19621 drwxrwxr-x 2 amrood amrood 4096 Dec 25 09:59 uml -rw-rw-r– 1 amrood amrood 5341 Dec 25 08:38 uml.jpg drwxr-xr-x 2 amrood amrood 4096 Feb 15 2006 univ drwxr-xr-x 2 root root 4096 Dec 9 2007 urlspedia -rw-r–r– 1 root root 276480 Dec 9 2007 urlspedia.tar drwxr-xr-x 8 root root 4096 Nov 25 2007 usr -rwxr-xr-x 1 root root 3192 Nov 25 2007 webthumb.php -rw-rw-r– 1 amrood amrood 20480 Nov 25 2007 webthumb.tar -rw-rw-r– 1 amrood amrood 5654 Aug 9 2007 yourfile.mid -rw-rw-r– 1 amrood amrood 166255 Aug 9 2007 yourfile.swf $ Here entries starting with d….. represent
Category: unix
Unix / Linux – Useful Commands ”; Previous Next This quick guide lists commands, including a syntax and a brief description. For more detail, use − $man command Files and Directories These commands allow you to create directories and handle files. Given below is the list of commands in Files and Directories. Sr.No. Command & Description 1 cat Displays File Contents 2 cd Changes Directory to dirname 3 chgrp Changes file group 4 chmod Changes permissions 5 cp Copies source file into destination 6 file Determines file type 7 find Finds files 8 grep Searches files for regular expressions 9 head Displays first few lines of a file 10 ln Creates softlink on oldname 11 ls Displays information about file type 12 mkdir Creates a new directory dirname 13 more Displays data in paginated form 14 mv Moves (Renames) an oldname to newname 15 pwd Prints current working directory 16 rm Removes (Deletes) filename 17 rmdir Deletes an existing directory provided it is empty 18 tail Prints last few lines in a file 19 touch Updates access and modification time of a file Manipulating data The contents of files can be compared and altered with the following commands. Given below is the list of commands in Manipulating data. Sr.No. Command & Description 1 awk Pattern scanning and processing language 2 cmp Compares the contents of two files 3 comm Compares sorted data 4 cut Cuts out selected fields of each line of a file 5 diff Differential file comparator 6 expand Expands tabs to spaces 7 join Joins files on some common field 8 perl Data manipulation language 9 sed Stream text editor 10 sort Sorts file data 11 split Splits file into smaller files 12 tr Translates characters 13 uniq Reports repeated lines in a file 14 wc Counts words, lines, and characters 15 vi Opens vi text editor 16 vim Opens vim text editor 17 fmt Simple text formatter 18 spell Checks text for spelling error 19 ispell Checks text for spelling error 20 emacs GNU project Emacs 21 ex, edit Line editor 22 emacs GNU project Emacs Compressed Files Files may be compressed to save space. Compressed files can be created and examined. Sr.No. Command & Description 1 compress Compresses files 2 gunzip Helps uncompress gzipped files 3 gzip GNU alternative compression method 4 uncompress Helps uncompress files 5 unzip List, test and extract compressed files in a ZIP archive 6 zcat Cat a compressed file 7 zcmp Compares compressed files 8 zdiff Compares compressed files 9 zmore File perusal filter for crt viewing of compressed text Getting Information Various Unix manuals and documentation are available on-line. The following Shell commands give information − Sr.No. Command & Description 1 apropos Locates commands by keyword lookup 2 info Displays command information pages online 2 man Displays manual pages online 3 whatis Searches the whatis database for complete words 4 yelp GNOME help viewer Network Communication These following commands are used to send and receive files from a local Unix hosts to the remote host around the world. Sr.No. Command & Description 1 ftp File transfer program 2 rcp Remote file copy 3 rlogin Remote login to a Unix host 4 rsh Remote shell 5 tftp Trivial file transfer program 6 telnet Makes terminal connection to another host 7 ssh Secures shell terminal or command connection 8 scp Secures shell remote file copy 9 sftp Secures shell file transfer program Some of these commands may be restricted at your computer for security reasons. Messages between Users The Unix systems support on-screen messages to other users and world-wide electronic mail − Sr.No. Command & Description 1 evolution GUI mail handling tool on Linux 2 mail Simple send or read mail program 3 mesg Permits or denies messages 4 parcel Sends files to another user 5 pine Vdu-based mail utility 6 talk Talks to another user 7 write Writes message to another user Programming Utilities The following programming tools and languages are available based on what you have installed on your Unix. Given below is the list of tools and languages in Programming Utilities. Sr.No. Command & Description 1 dbx Sun debugger 2 gdb GNU debugger 3 make Maintains program groups and compile programs 4 nm Prints program”s name list 5 size Prints program”s sizes 6 strip Removes symbol table and relocation bits 7 cb C program beautifier 8 cc ANSI C compiler for Suns SPARC systems 9 ctrace C program debugger 10 gcc GNU ANSI C Compiler 11 indent Indent and format C program source 12 bc Interactive arithmetic language processor 13 gcl GNU Common Lisp 14 perl General purpose language 15 php Web page embedded language 16 py Python language interpreter 17 asp Web page embedded language 18 CC C++ compiler for Suns SPARC systems 19 g++ GNU C++ Compiler 20 javac JAVA compiler 21 appletvieweir JAVA applet viewer 22 netbeans Java integrated development environment on Linux 23 sqlplus Runs the Oracle SQL interpreter 24 sqlldr Runs the Oracle SQL data loader 25 mysql Runs the mysql SQL interpreter Misc Commands These commands list or alter information about the system − Given below is the list of Misc Commands in Unix. Sr.No. Command & Description 1 chfn Changes your finger information 2 chgrp Changes the group ownership of a file 3 chown Changes owner 4 date Prints the date 5 determin Automatically finds terminal type 6 du Prints amount of disk usage 7 echo Echo arguments to the standard options 8 exit Quits the system 9 finger Prints information about logged-in users 10 groupadd Creates a user group 11 groups Show group memberships 12 homequota Shows quota and file usage 13 iostat Reports I/O statistics 14 kill Sends a signal to a process 15 last Shows last logins of users 16 logout Logs off Unix 17 lun Lists user names or login ID 18 netstat Shows network status 19 passwd Changes user password 20 passwd Changes your login password 21 printenv Displays value of a
Unix / Linux – User Administration ”; Previous Next In this chapter, we will discuss in detail about user administration in Unix. There are three types of accounts on a Unix system − Root account This is also called superuser and would have complete and unfettered control of the system. A superuser can run any commands without any restriction. This user should be assumed as a system administrator. System accounts System accounts are those needed for the operation of system-specific components for example mail accounts and the sshd accounts. These accounts are usually needed for some specific function on your system, and any modifications to them could adversely affect the system. User accounts User accounts provide interactive access to the system for users and groups of users. General users are typically assigned to these accounts and usually have limited access to critical system files and directories. Unix supports a concept of Group Account which logically groups a number of accounts. Every account would be a part of another group account. A Unix group plays important role in handling file permissions and process management. Managing Users and Groups There are four main user administration files − /etc/passwd − Keeps the user account and password information. This file holds the majority of information about accounts on the Unix system. /etc/shadow − Holds the encrypted password of the corresponding account. Not all the systems support this file. /etc/group − This file contains the group information for each account. /etc/gshadow − This file contains secure group account information. Check all the above files using the cat command. The following table lists out commands that are available on majority of Unix systems to create and manage accounts and groups − Sr.No. Command & Description 1 useradd Adds accounts to the system 2 usermod Modifies account attributes 3 userdel Deletes accounts from the system 4 groupadd Adds groups to the system 5 groupmod Modifies group attributes 6 groupdel Removes groups from the system You can use Manpage Help to check complete syntax for each command mentioned here. Create a Group We will now understand how to create a group. For this, we need to create groups before creating any account otherwise, we can make use of the existing groups in our system. We have all the groups listed in /etc/groups file. All the default groups are system account specific groups and it is not recommended to use them for ordinary accounts. So, following is the syntax to create a new group account − groupadd [-g gid [-o]] [-r] [-f] groupname The following table lists out the parameters − Sr.No. Option & Description 1 -g GID The numerical value of the group”s ID 2 -o This option permits to add group with non-unique GID 3 -r This flag instructs groupadd to add a system account 4 -f This option causes to just exit with success status, if the specified group already exists. With -g, if the specified GID already exists, other (unique) GID is chosen 5 groupname Actual group name to be created If you do not specify any parameter, then the system makes use of the default values. Following example creates a developers group with default values, which is very much acceptable for most of the administrators. $ groupadd developers Modify a Group To modify a group, use the groupmod syntax − $ groupmod -n new_modified_group_name old_group_name To change the developers_2 group name to developer, type − $ groupmod -n developer developer_2 Here is how you will change the financial GID to 545 − $ groupmod -g 545 developer Delete a Group We will now understand how to delete a group. To delete an existing group, all you need is the groupdel command and the group name. To delete the financial group, the command is − $ groupdel developer This removes only the group, not the files associated with that group. The files are still accessible by their owners. Create an Account Let us see how to create a new account on your Unix system. Following is the syntax to create a user”s account − useradd -d homedir -g groupname -m -s shell -u userid accountname The following table lists out the parameters − Sr.No. Option & Description 1 -d homedir Specifies home directory for the account 2 -g groupname Specifies a group account for this account 3 -m Creates the home directory if it doesn”t exist 4 -s shell Specifies the default shell for this account 5 -u userid You can specify a user id for this account 6 accountname Actual account name to be created If you do not specify any parameter, then the system makes use of the default values. The useradd command modifies the /etc/passwd, /etc/shadow, and /etc/group files and creates a home directory. Following is the example that creates an account mcmohd, setting its home directory to /home/mcmohd and the group as developers. This user would have Korn Shell assigned to it. $ useradd -d /home/mcmohd -g developers -s /bin/ksh mcmohd Before issuing the above command, make sure you already have the developers group created using the groupadd command. Once an account is created you can set its password using the passwd command as follows − $ passwd mcmohd20 Changing password for user mcmohd20. New UNIX password: Retype new UNIX password: passwd: all authentication tokens updated successfully. When you type passwd accountname, it gives you an option to change the password, provided you are a superuser. Otherwise, you can change just your password using the same command but without specifying your account name. Modify an Account The usermod command enables you to make changes to an existing account from the command line. It uses the same arguments as the useradd command, plus the -l argument, which allows you to change the account name. For example, to change the account name mcmohd to mcmohd20 and to change home directory accordingly, you will need to issue the following command − $ usermod -d /home/mcmohd20 -m -l mcmohd mcmohd20 Delete
Unix / Linux – Shell Quoting Mechanisms ”; Previous Next In this chapter, we will discuss in detail about the Shell quoting mechanisms. We will start by discussing the metacharacters. The Metacharacters Unix Shell provides various metacharacters which have special meaning while using them in any Shell Script and causes termination of a word unless quoted. For example, ? matches with a single character while listing files in a directory and an * matches more than one character. Here is a list of most of the shell special characters (also called metacharacters) − * ? [ ] ” ” $ ; & ( ) | ^ < > new-line space tab A character may be quoted (i.e., made to stand for itself) by preceding it with a . Example Following example shows how to print a * or a ? − Live Demo #!/bin/sh echo Hello; Word Upon execution, you will receive the following result − Hello ./test.sh: line 2: Word: command not found shell returned 127 Let us now try using a quoted character − Live Demo #!/bin/sh echo Hello; Word Upon execution, you will receive the following result − Hello; Word The $ sign is one of the metacharacters, so it must be quoted to avoid special handling by the shell − Live Demo #!/bin/sh echo “I have $1200″ Upon execution, you will receive the following result − I have $1200 The following table lists the four forms of quoting − Sr.No. Quoting & Description 1 Single quote All special characters between these quotes lose their special meaning. 2 Double quote Most special characters between these quotes lose their special meaning with these exceptions − $ ` $ ” “ \ 3 Backslash Any character immediately following the backslash loses its special meaning. 4 Back quote Anything in between back quotes would be treated as a command and would be executed. The Single Quotes Consider an echo command that contains many special shell characters − echo <-$1500.**>; (update?) [y|n] Putting a backslash in front of each special character is tedious and makes the line difficult to read − echo <-$1500.**>; (update?) [y|n] There is an easy way to quote a large group of characters. Put a single quote (”) at the beginning and at the end of the string − echo ”<-$1500.**>; (update?) [y|n]” Characters within single quotes are quoted just as if a backslash is in front of each character. With this, the echo command displays in a proper way. If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash () as follows − echo ”It”s Shell Programming The Double Quotes Try to execute the following shell script. This shell script makes use of single quote − Live Demo VAR=ZARA echo ”$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]” Upon execution, you will receive the following result − $VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ] This is not what had to be displayed. It is obvious that single quotes prevent variable substitution. If you want to substitute variable values and to make inverted commas work as expected, then you would need to put your commands in double quotes as follows − Live Demo VAR=ZARA echo “$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]” Upon execution, you will receive the following result − ZARA owes <-$1500.**>; [ as of (07/02) ] Double quotes take away the special meaning of all characters except the following − $ for parameter substitution Backquotes for command substitution $ to enable literal dollar signs ` to enable literal backquotes “ to enable embedded double quotes \ to enable embedded backslashes All other characters are literal (not special) Characters within single quotes are quoted just as if a backslash is in front of each character. This helps the echo command display properly. If a single quote appears within a string to be output, you should not put the whole string within single quotes instead you should precede that using a backslash () as follows − echo ”It”s Shell Programming” The Backquotes Putting any Shell command in between backquotes executes the command. Syntax Here is the simple syntax to put any Shell command in between backquotes − var=`command` Example The date command is executed in the following example and the produced result is stored in DATA variable. Live Demo DATE=`date` echo “Current Date: $DATE” Upon execution, you will receive the following result − Current Date: Thu Jul 2 05:28:45 MST 2009 Print Page Previous Next Advertisements ”;
Unix / Linux – Using Shell Variables ”; Previous Next In this chapter, we will learn how to use Shell variables in Unix. A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables. Variable Names The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the underscore character ( _). By convention, Unix shell variables will have their names in UPPERCASE. The following examples are valid variable names − _ALI TOKEN_A VAR_1 VAR_2 Following are the examples of invalid variable names − 2_VAR -VARIABLE VAR1-VAR2 VAR_A! The reason you cannot use other characters such as !, *, or – is that these characters have a special meaning for the shell. Defining Variables Variables are defined as follows − variable_name=variable_value For example − NAME=”Zara Ali” The above example defines the variable NAME and assigns the value “Zara Ali” to it. Variables of this type are called scalar variables. A scalar variable can hold only one value at a time. Shell enables you to store any value you want in a variable. For example − VAR1=”Zara Ali” VAR2=100 Accessing Values To access the value stored in a variable, prefix its name with the dollar sign ($) − For example, the following script will access the value of defined variable NAME and print it on STDOUT − Live Demo #!/bin/sh NAME=”Zara Ali” echo $NAME The above script will produce the following value − Zara Ali Read-only Variables Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed. For example, the following script generates an error while trying to change the value of NAME − Live Demo #!/bin/sh NAME=”Zara Ali” readonly NAME NAME=”Qadiri” The above script will generate the following result − /bin/sh: NAME: This variable is read only. Unsetting Variables Unsetting or deleting a variable directs the shell to remove the variable from the list of variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable. Following is the syntax to unset a defined variable using the unset command − unset variable_name The above command unsets the value of a defined variable. Here is a simple example that demonstrates how the command works − #!/bin/sh NAME=”Zara Ali” unset NAME echo $NAME The above example does not print anything. You cannot use the unset command to unset variables that are marked readonly. Variable Types When a shell is running, three main types of variables are present − Local Variables − A local variable is a variable that is present within the current instance of the shell. It is not available to programs that are started by the shell. They are set at the command prompt. Environment Variables − An environment variable is available to any child process of the shell. Some programs need environment variables in order to function correctly. Usually, a shell script defines only those environment variables that are needed by the programs that it runs. Shell Variables − A shell variable is a special variable that is set by the shell and is required by the shell in order to function correctly. Some of these variables are environment variables whereas others are local variables. Print Page Previous Next Advertisements ”;
Unix / Linux – Discussion
Discuss Unix / Linux ”; Previous Next Unix is a computer Operating System which is capable of handling activities from multiple users at the same time. The development of Unix started around 1969 at AT&T Bell Labs by Ken Thompson and Dennis Ritchie. This tutorial gives a very good understanding on Unix. Print Page Previous Next Advertisements ”;
Unix / Linux – Shell Basic Operators ”; Previous Next There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter. We will now discuss the following operators − Arithmetic Operators Relational Operators Boolean Operators String Operators File Test Operators Bourne shell didn”t originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr. The following example shows how to add two numbers − Live Demo #!/bin/sh val=`expr 2 + 2` echo “Total value : $val” The above script will generate the following result − Total value : 4 The following points need to be considered while adding − There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2. The complete expression should be enclosed between ‘ ‘, called the backtick. Arithmetic Operators The following arithmetic operators are supported by Bourne Shell. Assume variable a holds 10 and variable b holds 20 then − Show Examples Operator Description Example + (Addition) Adds values on either side of the operator `expr $a + $b` will give 30 – (Subtraction) Subtracts right hand operand from left hand operand `expr $a – $b` will give -10 * (Multiplication) Multiplies values on either side of the operator `expr $a * $b` will give 200 / (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2 % (Modulus) Divides left hand operand by right hand operand and returns remainder `expr $b % $a` will give 0 = (Assignment) Assigns right operand in left operand a = $b would assign value of b into a == (Equality) Compares two numbers, if both are same then returns true. [ $a == $b ] would return false. != (Not Equality) Compares two numbers, if both are different then returns true. [ $a != $b ] would return true. It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect. All the arithmetical calculations are done using long integers. Relational Operators Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric. For example, following operators will work to check a relation between 10 and 20 as well as in between “10” and “20” but not in between “ten” and “twenty”. Assume variable a holds 10 and variable b holds 20 then − Show Examples Operator Description Example -eq Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a -eq $b ] is not true. -ne Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. [ $a -ne $b ] is true. -gt Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. [ $a -gt $b ] is not true. -lt Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. [ $a -lt $b ] is true. -ge Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -ge $b ] is not true. -le Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -le $b ] is true. It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect. Boolean Operators The following Boolean operators are supported by the Bourne Shell. Assume variable a holds 10 and variable b holds 20 then − Show Examples Operator Description Example ! This is logical negation. This inverts a true condition into false and vice versa. [ ! false ] is true. -o This is logical OR. If one of the operands is true, then the condition becomes true. [ $a -lt 20 -o $b -gt 100 ] is true. -a This is logical AND. If both the operands are true, then the condition becomes true otherwise false. [ $a -lt 20 -a $b -gt 100 ] is false. String Operators The following string operators are supported by Bourne Shell. Assume variable a holds “abc” and variable b holds “efg” then − Show Examples Operator Description Example = Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a = $b ] is not true. != Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true. [ $a != $b ] is true. -z Checks if the given string operand size is zero; if it is zero length, then it returns true. [ -z $a ] is not true. -n Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true. [ -n $a ] is not false. str Checks if str is not the empty string; if it is empty, then it returns false. [ $a ] is not false. File Test Operators We have a few operators that can be used to test various properties associated with a Unix file. Assume a variable file holds an existing file name “test” the size of which is 100 bytes and has read, write and execute permission on − Show Examples Operator Description Example -b file Checks if file is a block special file; if yes, then the condition becomes true.
Unix / Linux – System Logging ”; Previous Next In this chapter, we will discuss in detail about system logging in Unix. Unix systems have a very flexible and powerful logging system, which enables you to record almost anything you can imagine and then manipulate the logs to retrieve the information you require. Many versions of Unix provide a general-purpose logging facility called syslog. Individual programs that need to have information logged, send the information to syslog. Unix syslog is a host-configurable, uniform system logging facility. The system uses a centralized system logging process that runs the program /etc/syslogd or /etc/syslog. The operation of the system logger is quite straightforward. Programs send their log entries to syslogd, which consults the configuration file /etc/syslogd.conf or /etc/syslog and, when a match is found, writes the log message to the desired log file. There are four basic syslog terms that you should understand − Sr.No. Term & Description 1 Facility The identifier used to describe the application or process that submitted the log message. For example, mail, kernel, and ftp. 2 Priority An indicator of the importance of the message. Levels are defined within syslog as guidelines, from debugging information to critical events. 3 Selector A combination of one or more facilities and levels. When an incoming event matches a selector, an action is performed. 4 Action What happens to an incoming message that matches a selector — Actions can write the message to a log file, echo the message to a console or other device, write the message to a logged in user, or send the message along to another syslog server. Syslog Facilities We will now understand about the syslog facilities. Here are the available facilities for the selector. Not all facilities are present on all versions of Unix. Facility Description 1 auth Activity related to requesting name and password (getty, su, login) 2 authpriv Same as auth but logged to a file that can only be read by selected users 3 console Used to capture messages that are generally directed to the system console 4 cron Messages from the cron system scheduler 5 daemon System daemon catch-all 6 ftp Messages relating to the ftp daemon 7 kern Kernel messages 8 local0.local7 Local facilities defined per site 9 lpr Messages from the line printing system 10 mail Messages relating to the mail system 11 mark Pseudo-event used to generate timestamps in log files 12 news Messages relating to network news protocol (nntp) 13 ntp Messages relating to network time protocol 14 user Regular user processes 15 uucp UUCP subsystem Syslog Priorities The syslog priorities are summarized in the following table − Sr.No. Priority & Description 1 emerg Emergency condition, such as an imminent system crash, usually broadcast to all users 2 alert Condition that should be corrected immediately, such as a corrupted system database 3 crit Critical condition, such as a hardware error 4 err Ordinary error 5 Warning Warning 6 notice Condition that is not an error, but possibly should be handled in a special way 7 info Informational message 8 debug Messages that are used when debugging programs 9 none Pseudo level used to specify not to log messages The combination of facilities and levels enables you to be discerning about what is logged and where that information goes. As each program sends its messages dutifully to the system logger, the logger makes decisions on what to keep track of and what to discard based on the levels defined in the selector. When you specify a level, the system will keep track of everything at that level and higher. The /etc/syslog.conf file The /etc/syslog.conf file controls where messages are logged. A typical syslog.conf file might look like this − *.err;kern.debug;auth.notice /dev/console daemon,auth.notice /var/log/messages lpr.info /var/log/lpr.log mail.* /var/log/mail.log ftp.* /var/log/ftp.log auth.* @prep.ai.mit.edu auth.* root,amrood netinfo.err /var/log/netinfo.log install.* /var/log/install.log *.emerg * *.alert |program_name mark.* /dev/console Each line of the file contains two parts − A message selector that specifies which kind of messages to log. For example, all error messages or all debugging messages from the kernel. An action field that says what should be done with the message. For example, put it in a file or send the message to a user”s terminal. Following are the notable points for the above configuration − Message selectors have two parts: a facility and a priority. For example, kern.debug selects all debug messages (the priority) generated by the kernel (the facility). Message selector kern.debug selects all priorities that are greater than debug. An asterisk in place of either the facility or the priority indicates “all”. For example, *.debug means all debug messages, while kern.* means all messages generated by the kernel. You can also use commas to specify multiple facilities. Two or more selectors can be grouped together by using a semicolon. Logging Actions The action field specifies one of five actions − Log message to a file or a device. For example, /var/log/lpr.log or /dev/console. Send a message to a user. You can specify multiple usernames by separating them with commas; for example, root, amrood. Send a message to all users. In this case, the action field consists of an asterisk; for example, *. Pipe the message to a program. In this case, the program is specified after the Unix pipe symbol (|). Send the message to the syslog on another host. In this case, the action field consists of a hostname, preceded by an at sign; for example, @tutorialspoint.com. The logger Command Unix provides the logger command, which is an extremely useful command to deal with system logging. The logger command sends logging messages to the syslogd daemon, and consequently provokes system logging. This means we can check from the command line at any time the syslogd daemon and its configuration. The logger command provides a method for adding one-line entries to the system log file from the command line. The format of the command is − logger [-i] [-f file] [-p priority] [-t tag] [message]… Here
Unix / Linux – Useful Resources ”; Previous Next The following resources contain additional information on Unix / Linux. Please use them to get more in-depth knowledge on this. Unix and Linux System Administration Fundamentals Course Most Popular 130 Lectures 23 hours Eduonix Learning Solutions More Detail Essentials of Unix Operating System 6 Lectures 4.5 hours Frahaan Hussain More Detail Unix Command Course For Beginners 36 Lectures 2 hours Pradeep D More Detail Print Page Previous Next Advertisements ”;
Unix / Linux – Signals and Traps ”; Previous Next In this chapter, we will discuss in detail about Signals and Traps in Unix. Signals are software interrupts sent to a program to indicate that an important event has occurred. The events can vary from user requests to illegal memory access errors. Some signals, such as the interrupt signal, indicate that a user has asked the program to do something that is not in the usual flow of control. The following table lists out common signals you might encounter and want to use in your programs − Signal Name Signal Number Description SIGHUP 1 Hang up detected on controlling terminal or death of controlling process SIGINT 2 Issued if the user sends an interrupt signal (Ctrl + C) SIGQUIT 3 Issued if the user sends a quit signal (Ctrl + D) SIGFPE 8 Issued if an illegal mathematical operation is attempted SIGKILL 9 If a process gets this signal it must quit immediately and will not perform any clean-up operations SIGALRM 14 Alarm clock signal (used for timers) SIGTERM 15 Software termination signal (sent by kill by default) List of Signals There is an easy way to list down all the signals supported by your system. Just issue the kill -l command and it would display all the supported signals − $ kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX The actual list of signals varies between Solaris, HP-UX, and Linux. Default Actions Every signal has a default action associated with it. The default action for a signal is the action that a script or program performs when it receives a signal. Some of the possible default actions are − Terminate the process. Ignore the signal. Dump core. This creates a file called core containing the memory image of the process when it received the signal. Stop the process. Continue a stopped process. Sending Signals There are several methods of delivering signals to a program or script. One of the most common is for a user to type CONTROL-C or the INTERRUPT key while a script is executing. When you press the Ctrl+C key, a SIGINT is sent to the script and as per defined default action script terminates. The other common method for delivering signals is to use the kill command, the syntax of which is as follows − $ kill -signal pid Here signal is either the number or name of the signal to deliver and pid is the process ID that the signal should be sent to. For Example − $ kill -1 1001 The above command sends the HUP or hang-up signal to the program that is running with process ID 1001. To send a kill signal to the same process, use the following command − $ kill -9 1001 This kills the process running with process ID 1001. Trapping Signals When you press the Ctrl+C or Break key at your terminal during execution of a shell program, normally that program is immediately terminated, and your command prompt returns. This may not always be desirable. For instance, you may end up leaving a bunch of temporary files that won”t get cleaned up. Trapping these signals is quite easy, and the trap command has the following syntax − $ trap commands signals Here command can be any valid Unix command, or even a user-defined function, and signal can be a list of any number of signals you want to trap. There are two common uses for trap in shell scripts − Clean up temporary files Ignore signals Cleaning Up Temporary Files As an example of the trap command, the following shows how you can remove some files and then exit if someone tries to abort the program from the terminal − $ trap “rm -f $WORKDIR/work1$$ $WORKDIR/dataout$$; exit” 2 From the point in the shell program that this trap is executed, the two files work1$$ and dataout$$ will be automatically removed if signal number 2 is received by the program. Hence, if the user interrupts the execution of the program after this trap is executed, you can be assured that these two files will be cleaned up. The exit command that follows the rm is necessary because without it, the execution would continue in the program at the point that it left off when the signal was received. Signal number 1 is generated for hangup. Either someone intentionally hangs up the line or the line gets accidentally disconnected. You can modify the preceding trap to also remove the two specified files in this case by adding signal number 1 to the list of signals − $ trap “rm $WORKDIR/work1$$ $WORKDIR/dataout$$; exit” 1 2 Now these files will be removed if the line gets hung up or if the Ctrl+C key gets pressed. The commands specified to trap must be enclosed in quotes, if they contain more than one command. Also note that the shell scans the command line at the time that the trap command gets executed and also when one of the listed signals is received. Thus, in the preceding example, the value of WORKDIR and $$ will be substituted at the time that the trap command is executed. If you wanted this substitution to occur at the time that either signal 1 or