Skip to main content

Unix Basic step by step

What is Unix ?

The UNIX operating system is a set of programs that act as a link between the computer and the user.
  • Unix was originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Douglas McIlroy, and Joe Ossanna.
  • There are various Unix variants available in the market. Solaris Unix, AIX, UP Unix and BSD are few examples. Linux is also a flavour 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 called multitasking.

Login Unix:

You can login to the system using login command as follows:
login : ryu
ryu's password:
Last login: Sun Jun 14 09:32:32 2009 from 62.61.164.73
[ryu]$

Logging Out:

When you finish your session, you need to log out of the system to ensure that nobody else accesses your files while masquerading as you.

To log out:

  1. Just type logout command at command prompt, and the system will clean up everything and break the connection

File Management:

In UNIX there are three basic types of files:
  1. Ordinary Files: An ordinary file is a file on the system that contains data, text, or program instructions. In this tutorial, you look at working with ordinary files.
  2. Directories: Directories store both special and ordinary files. For users familiar with Windows or Mac OS, UNIX directories are equivalent to folders.
  3. Special Files: Some special files provide access to hardware such as hard drives, CD-ROM drives, modems, and Ethernet adapters. Other special files are similar to aliases or shortcuts and enable you to access a single file using different names.

Filename Substitution:

CommandDescription
ls -[l]List Files in Current Directory
ls -[l]aList Hidden Files
~Home Directory
~userHome Directory of Another User
?Wild Card, matches single character
*Wild Card, matches multiple characters

Filename Manipulation:

CommandDescription
cat filenameDisplay File Contents
cp source destinationCopy source file into destination
mv oldname newnameMove (Rename) a oldname to newname.
rm filenameRemove (Delete) filename
chmod nnn filenameChanging Permissions
touch filenameChanging Modification Time
ln [-s] oldname newnameCreates softlink on oldname
ls -FDisplay information about file type.

Directory Management:

CommandDescription
mkdir dirnameCreate a new directory dirname
rmdir dirnameDelete an existing directory provided it is empty.
cd dirnameChange Directory to dirname
cd -Change to last working directory.
cd ~Change to home directory
pwdDisplay current working directory.

Environment Setup:

When you type any command on command prompt, the shell has to locate the command before it can be executed. The PATH variable specifies the locations in which the shell should look for commands.

PS1 and PS2 Variables:

The characters that the shell displays as your command prompt are stored in the variable PS1.
When you issue a command that is incomplete, the shell will display a secondary prompt and wait for you to complete the command and hit Enter again. The default secondary prompt is > (the greater than sign), but can be changed by re-defining the PS2 shell variable:

Escape Characters:

Escape SequenceDescription
\tCurrent time, expressed as HH:MM:SS.
\dCurrent date, expressed as Weekday Month Date
\nNewline.
\sCurrent shell environment.
\WWorking directory.
\wFull path of the working directory.
\uCurrent user.s username.
\hHostname of the current machine.
\#Command number of the current command. Increases with each new command entered.
\$If the effective UID is 0 (that is, if you are logged in as root), end the prompt with the # character; otherwise, use the $.

Environment Variables:

Following is the partial list of important environment variables. These variables would be set and accessed as mentioned above:
VariableDescription
DISPLAY Contains the identifier for the display that X11 programs should use by default.
HOMEIndicates the home directory of the current user: the default argument for the cd built-in command.
IFSIndicates the Internal Field Separator that is used by the parser for word splitting after expansion.
LANGLANG expands to the default system locale; LC_ALL can be used to override this. For example, if its value is pt_BR, then the language is set to (Brazilian) Portuguese and the locale to Brazil.
LD_LIBRARY_PATH On many Unix systems with a dynamic linker, contains a colon-separated list of directories that the dynamic linker should search for shared objects when building a process image after exec, before searching in any other directories.
PATHIndicates search path for commands. It is a colon-separated list of directories in which the shell looks for commands.
PWDIndicates the current working directory as set by the cd command.
RANDOMGenerates a random integer between 0 and 32,767 each time it is referenced.
SHLVLIncrements by one each time an instance of bash is started. This variable is useful for determining whether the built-in exit command ends the current session.
TERM Refers to the display type
TZ Refers to Time zone. It can take values like GMT, AST, etc.
UIDExpands to the numeric user ID of the current user, initialized at shell startup.

Filters & Pipes:

CommandDescription
wc [-l] Word/Line Count
tail [-n] Displays last n lines from a file
sort [-n] Sort lines
pr -t Multicolumn Output
grep "pattern" filename Searching for a pattern with grep
pg or more Paginate a file content display.

Special Variables

VariableDescription
$0The filename of the current script.
$nThese variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).
$#The number of arguments supplied to a script.
$*All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.
$@All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.
$?The exit status of the last command executed.
$$The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
$!The process number of the last background command.

Shell Basic Operators

Arithmetic Operators:

Assume variable a holds 10 and variable b holds 20 then:
OperatorDescriptionExample
+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 - Assign right operand in left operanda=$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.

Relational Operators:

Assume variable a holds 10 and variable b holds 20 then:
OperatorDescriptionExample
-eqChecks if the value of two operands are equal or not, if yes then condition becomes true.[ $a -eq $b ] is not true.
-neChecks if the value of two operands are equal or not, if values are not equal then condition becomes true.[ $a -ne $b ] is true.
-gtChecks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.[ $a -gt $b ] is not true.
-ltChecks if the value of left operand is less than the value of right operand, if yes then condition becomes true.[ $a -lt $b ] is true.
-geChecks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.[ $a -ge $b ] is not true.
-leChecks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.[ $a -le $b ] is true.

Boolean Operators:

Assume variable a holds 10 and variable b holds 20 then:
OperatorDescriptionExample
!This is logical negation. This inverts a true condition into false and vice versa.[ ! false ] is true.
-oThis is logical OR. If one of the operands is true then condition would be true.[ $a -lt 20 -o $b -gt 100 ] is true.
-aThis is logical AND. If both the operands are true then condition would be true otherwise it would be false.[ $a -lt 20 -a $b -gt 100 ] is false.

String Operators:

Assume variable a holds "abc" and variable b holds "efg" then:
OperatorDescriptionExample
=Checks if the value of two operands are equal or not, if yes then 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 condition becomes true.[ $a != $b ] is true.
-zChecks if the given string operand size is zero. If it is zero length then it returns true.[ -z $a ] is not true.
-nChecks if the given string operand size is non-zero. If it is non-zero length then it returns true.[ -z $a ] is not false.
strCheck if str is not the empty string. If it is empty then it returns false.[ $a ] is not false.

File Test Operators:

Assume a variable file holds an existing file name "test" whose size is 100 bytes and has read, write and execute permission on:
OperatorDescriptionExample
-b fileChecks if file is a block special file if yes then condition becomes true.[ -b $file ] is false.
-c fileChecks if file is a character special file if yes then condition becomes true.[ -b $file ] is false.
-d fileCheck if file is a directory if yes then condition becomes true.[ -d $file ] is not true.
-f fileCheck if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true.[ -f $file ] is true.
-g fileChecks if file has its set group ID (SGID) bit set if yes then condition becomes true.[ -g $file ] is false.
-k fileChecks if file has its sticky bit set if yes then condition becomes true.[ -k $file ] is false.
-p fileChecks if file is a named pipe if yes then condition becomes true.[ -p $file ] is false.
-t fileChecks if file descriptor is open and associated with a terminal if yes then condition becomes true.[ -t $file ] is false.
-u fileChecks if file has its set user id (SUID) bit set if yes then condition becomes true.[ -u $file ] is false.
-r fileChecks if file is readable if yes then condition becomes true.[ -r $file ] is true.
-w fileCheck if file is writable if yes then condition becomes true.[ -w $file ] is true.
-x fileCheck if file is execute if yes then condition becomes true.[ -x $file ] is true.
-s fileCheck if file has size greater than 0 if yes then condition becomes true.[ -s $file ] is true.
-e fileCheck if file exists. Is true even if file is a directory but exists.[ -e $file ] is true.

Shell Decision Making

The if...fi statement:

if [ expression ]
then
Statement(s) to be executed if expression is true
fi

The if...else...fi statement:

if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi

The if...elif...fi statement:

if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]

then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi

The case...esac Statement:

case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches

;;
esac

Shell Loop Types:

The while Loop:

while command
do
Statement(s) to be executed if command is true
done

The for Loop:

for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done

The until Loop:

until command
do
Statement(s) to be executed until command is true
done

The select Loop:

select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done

Shell Loop Control:

The break statement:

break [n]

The continue statement:

continue [n]

Shell Substitutions:

The shell performs substitution when it encounters an expression that contains one or more special characters.

Command Substitution:

The command substitution is performed when a command is given as:
`command`

Variable Substitution:

Here is the following table for all the possible substitutions:
FormDescription
${var}Substitue the value of var.
${var:-word}If var is null or unset, word is substituted for var. The value of var does not change.
${var:=word}If var is null or unset, var is set to the value of word.
${var:?message}If var is null or unset, message is printed to standard error. This checks that variables are set correctly.
${var:+word}If var is set, word is substituted for var. The value of var does not change.

Redirection Commands:

Following is the complete list of commands which you can use for redirection:
CommandDescription
pgm > fileOutput of pgm is redirected to file
pgm < fileProgram pgm reads its input from file.
pgm >> fileOutput of pgm is appended to file.
n > fileOutput from stream with descriptor n redirected to file.
n >> fileOutput from stream with descriptor n appended to file.
n >& mMerge output from stream n with stream m.
n <& mMerge input from stream n with stream m.
<< tag Standard input comes from here through next tag at start of line.
|Takes output from one program, or process, and sends it to another.

Shell Man Pages Help:

This quick guide lists commands, including a syntax and brief description. For more detail, use:
$man command

Comments

Last Week Topics

How to break a bonded network interface red hat

1.- Bonding device called bond0 which aggregated by eth0 and eth1 # ifconfig bond0     Link encap:Ethernet  HWaddr 44:a8:42:5d:6d:5d           inet addr:192.168.1.51  Bcast:192.168.1.255  Mask:255.255.255.0           inet6 addr: fe80::5054:ff:fe4d:9004/64 Scope:Link           UP BROADCAST RUNNING MASTER MULTICAST  MTU:1500  Metric:1 eth0      Link encap:Ethernet  HWaddr 44:a8:42:5d:6d:5d           UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1 eth2      Link encap:Ethernet  HWaddr 44:a8:42:5d:76:29           UP BROADCAST RUNNING SLAVE MULTICAST  MTU:1500  Metric:1           RX packets:6 errors:0 dropped:0 overruns:0 frame:0 # cat /proc/net/bonding/bond0 Ethernet Channel Bonding Driver: v3.6.0 (September 26, 2009) Bonding Mode: fault-tolerance (active-backup) Primary Slave: em1 (primary_reselect always) Currently Active Slave: em1 MII Status: up MII Polling Interval (ms): 50 Up Delay (ms): 0 Down Delay (ms): 0 Slave Interface: eth0 MII Status: up Speed: 10000

HOW TO ADD A LINE WITH ANSIBLE WITH TAB SPACE IN A FILE

-bash-4.2# vi add_line_syslog.yml --- - name: script in order to add in the server list below with TAB spaces a Line in the SYSLOG CONF   hosts: oraking   tasks:     - name: Add a Line  in /etc/syslog.conf in order to delivery that information to another server       lineinfile:         path: /etc/syslog.conf         line: " *.err;auth.notice;auth.info;local0.info \t\t @10.10.10.200 "         insertbefore: ' \*.alert;kern.err;daemon.err '     - name: Restart system-log       command: /usr/sbin/svcadm restart svc:/system/system-log:default

How to configure publisher and install packages in Oracle Solaris 11

Connect to Oracle Support and Download the certificates Set proxy if you have one  #export https_proxy=https://usuario:password@191.118.2.110:8080  #export http_proxy=http://usuario:password@191.118.2.110:8080 You can add in the profile this information in order to have them configured in the login 1.-Download the ssl certicates in order to install them in the server 2.-Create a directory /var/pkg/ssl. #mkdir -p 755  /var/pkg/ssl 3.-Copy or Move the cerrtificates  # cd /var/pkg/ssl/  # ls -ltr total 53 -rw-r--r--   1 root     root        1679 Mar 27 13:36 Oracle_Solaris_11_Support.key.pem -rw-r--r--   1 root     root         932 Mar 27 13:36 Oracle_Solaris_11_Support.certificate.pem 4.- # pkg set-publisher \  -k /var/pkg/ssl/Oracle_Solaris_11_Support.key.pem \ -c /var/pkg/ssl/Oracle_Solaris_11_Support.certificate.pem \ -g https://pkg.oracle.com/solaris/support/ \ -G http://pkg.oracle.com/solaris/release/ solaris   5.-Verify the new publisher  # pkg publ

Updating Solaris 11.X to 11.3 and SRU to 11.3.2.4.0

Updating Solaris 11.X to 11.3 Download Repository Certificate s accessing with MOS user https://pkg-register.oracle.com/register/certificate/ Upload them to the server and rename as below pkg.oracle.com.certificate.perm pkg.oracle.com.key.perm root@:~# pkg unset-publisher This option below delete the currently repository and add the new one root@:~# pkg set-publisher -k  /root/pkg.oracle.com.key.pem -c /root/pkg.oracle.com.certificate.pem -G "*" -g https://pkg.oracle.com/solaris/support/ solaris root@:~# pkg publisher PUBLISHER                   TYPE     STATUS P LOCATION solaris                     origin   online F http://pkg.oracle.com/solaris/support/ root@# pkg update Validate previous boot environment root@:~# beadm list BE      Flags Mountpoint Space  Policy Created --      ----- ---------- -----  ------ ------- solaris NR    /          12.58G static 2016-03-15 07:11 root@:~# root@:~# PHASE             

HOW TO SHARE WITH ZFS A FILE SYSTEM IN SOLARIS 11

As root execute the following Create the pool #zpool create ztemp c0d0 Create ZFS  #zfs create ztemp/temp Mount ZFS  #zfs set mountpoint=/temp ztemp/temp Share ZFS with the option "sharenfs=on" #zfs set sharenfs=on ztemp/temp Share and Select the PATH and SERVERS that you need that mount the ZFS from the NFS Server in our case the servers are oracle1,oracle2 and oracle3 with Read and Write Options #zfs set share=name=temp,path=/temporario,prot=nfs,anon=0,rw=oracle1:oracle2:oracle3 ztemp/temp

How to install Explorer Data Collector 8.11 Solaris 11

1.-Download from Oracle Support MOS the patch 22783063 and unzip and run the command below p22783063_8111638_SOLARIS64.zip #./install_stb.sh -verbose Extracting the STB payload ... Determining the check sums ... Sourcing STB library file ... List of Services Tool Bundle Components:    Oracle Explorer Data Collector 8.11    Oracle Serial Number in EEPROM (SNEEP) 8.11    Service Tag (ST) packages    Oracle Autonomous Crashdump Tool 8.17 (ACT) Would you like to (I)nstall, (X)tract, or (E)xit ? (I by default) X  <-----Select Extract (X) Extracting components for Solaris 11/sparc ...  Extracting IPS repository  Extracting SVR4 packages for Service Tag (ST) packages  - Package 5.11_sparc/SUNWsthwreg.sparc.5.10.pkg extracted Extraction to /var/tmp/stb/extract done Removing STB installation area ...   2.- Now you have in the directory "/var/tmp/stb/extract" de ipsrepo  # cd /var/tmp/stb/extract rwxr-xr-x   3 102      staff          4 Mar  8 11:28 ipsrepo -rw-r--r-- 

How to see all spfile parameters

SET LINESIZE 300 COLUMN name  FORMAT A30 COLUMN value FORMAT A60 COLUMN displayvalue FORMAT A60 SELECT sp.sid,        sp.name,        sp.value,        sp.display_value FROM   v$spparameter sp ORDER BY sp.name, sp.sid;

What is PaaS, IaaS and SaaS?

  Infrastructure Platform as a Service (iPaaS) Integration Platform as a Service (iPaaS) is a suite of cloud services enabling the development, execution, and governance of integration flows connecting any combination of on-premises and cloud-based processes, services, applications, and data within individuals or across multiple organizations.   Ease of use Comprehensive integration of toolsets   Level of support   Readiness to support protocols Flexibility Ability to process, clean, and transform data in formats like XML and JSON; Performance when handling large-scale data operations and concurrent executions; Support for real-time processing and batch data integration; Monitoring for failures, latency, resource utilization, and workflow performance;   Security mechanisms for access control, data encryption, and single sign-on integrations   Infrastructure as a Service (IaaS)     I s a business model that delivers IT infrastructure like computing, storage, and network resources on a p

How to Reset the Root Password of RHEL-7 / systemd

1) Boot your system and wait until the GRUB2 menu appears. 2) In the boot loader menu, highlight any entry and press e . 3) Find the line beginning with linux. At the end of this line, append the following: init=/bin/sh Or if you face a panic, instead of "ro" change to "rw" to sysroot as example below: rw init=/sysroot/bin/sh 4) Press F10 or Ctrl+X to boot the system using the options you just edited. Once the system boots, you will be presented with a shell prompt without having to enter any user name or password: sh-4.2# 5) Load the installed SELinux policy: sh-4.2# /usr/sbin/load_policy -i 6) Execute the following command to remount your root partition: sh4.2# mount -o remount,rw / 7) Reset the root password: Raw sh4.2# passwd root 9) Reboot the system. From now on, you will be able to log in as the root user using the new password set up during this procedure.