Below are the most commonly used Unix / Shell scripting commands.
VI Editor
:q ———————————-> QUIT
:q! ———————————-> QUIT WITHOUT SAVING
:w ———————————> Save
:wq ——————————–> save and quit
:w fileName ——————————> save as fileName
These are in Command mode:
Syntax:
[Count] command [where]
x ---> delete character under the cursor.
X ---> Delete the character before the cursor.
u--> Undo,
D-> Delete till the end of the line
i --> Insert
a --> Append
r --> Replace the word under the cursor
R --> Replace everything (overwrite text)
It cuts the data in command mode
d^ deletes from current cursor position to the beginning of the line.
d$ deletes from current cursor position to the end of the line.
dw deletes from current cursor position to the end of the word.
dd deletes 1 lines from current cursor position downwards
3dd deletes three lines from current cursor position downwards.
Y–> Yank (copy) the current line.
P -> Paste the line
dd –> It will cut the line, so that you can paste it with “P”
:/word_to_search (searches from top to bottom)
:?word_to_search (searches from bottom to top)
N -> repeat the last search given by “:/” or “:?”
n —> Move the cursor to the next match
:set nu —> will display line numbers in VI editor.
:set nonu —> Hide line numbers
:set wm=3 ——-> sets the warpmargin to be three characters from the right of the screen. This gives me a nice wordwrap.
: set sm ———> The second line sets showmatch so that whenever I type a }, ) or ], it shows the matching brace, parenthesis, or bracket. This is useful for the programming I do.
:set ic ——–> Set Ignore Case during searches.
:set ai ——–> Set Auto Indentation during text entry.
End of the file in VI editor-à G
Beginning of the file in VI editor à 1G (or gg)
Go to 10th line of the file in VI editor —-à 10G
$—à end of the current line in Vi
^—à beginning of the current line in vi
:Line_number –à Cursor will go to that line.
|
* |
:x<Return> | quit vi, writing out modified file to file named in original invocation |
|
|
:wq<Return> | quit vi, writing out modified file to file named in original invocation |
|
|
:q<Return> | quit (or exit) vi |
|
* |
:q!<Return> | quit vi even though latest changes have not been saved for this vi call |
Vim editor
It will show the shell script code in color.
Example:
vim test.sh
To change the colors, do :
Escape —à “:” —à colorscheme —-à space tab (It will show the possible colors)
Selecting default will take you back.
Use vi shortcuts in terminal
Many Unix shells (bash, zsh, etc.) come with keyboard shortcuts enabled: C-a jumps to the start of the line, C-e jumps to the end, and so on. However, these are taken from Emacs. It’s possible to tell your shell to use Vi shortcuts instead. Not only will the keybindings match what you’re used to, but you’ll also have modal editing, just like Vi.
To enable Vi-mode, edit (or create) the file ~/.inputrc or /etc/inputrc and add the following lines:
set editing-mode vi
set keymap vi-command
Searching in vi or vim editor
Escape –à / –à search_string. ( It will highlight the first search_string)
You can move to the next one by pressing the “n” button.
TO SEE THE CRON SCRIPTS
crontab –l
TO EDIT THE CRONS
crontab –e (IT will open in a VI editor, once you edit it and save, it will install the new crontab, it automatically means you configured crontab)
# .—————- minute (0 – 59)
# | .————- hour (0 – 23)
# | | .———- day of month (1 – 31)
# | | | .——- month (1 – 12) OR jan,feb,mar,apr …
# | | | | .—- day of week(0-6)(Sunday=0 or 7)OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
Special String for Cron
# Names can also be used for the month and week day fields. Use the first three
# letters of the particular day or month (case doesn’t matter). Ranges or
# lists of names are not allowed.
#
# @reboot : Run once, at startup.
# @yearly : Run once a year, ie. “0 0 1 1 *”
# @annually : Run once a year, ie. “0 0 1 1 *”
# @monthly : Run once a month, ie. “0 0 1 * *”
# @weekly : Run once a week, ie. “0 0 * * 0”
# @daily : Run once a day, ie. “0 0 * * *”
# @hourly : Run once an hour, ie. “0 * * * *”
#
##################################################
Character / Word substitution
Syntax of the text substitution inside vim editor:
:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
Example: %s/13105/13205/g
Following are three possible flags.
- [c] Confirm each substitution.
- [g] Replace all occurrences in the line.
- [i] Ignore case for the pattern.
This is the basic fundamental usage of the text substitution inside VI editor. When you want a specific text to be replaced with another text in the entire file then you can use the following sequence.
: %s/old-text/new-text/g
- %s – specifies all lines. Specifying the range as ‘%’ means do substitution in the entire file.
- g – Specifies all occurrences in the line. With the ‘g’ flag, you can make the whole line to be substituted. If this ‘g’ flag is not used then only first occurrence in the line only will be substituted.
Use: “sh –x” to run the script in Debug Mode
To run the script in debug mode
Ex :
sh -x tibemsadmin_wrapper.ksh -e prod
Linux and Unix wc command
wc [-c | -m | -C ] [-l] [-w] [ file … ]
| -c | Count bytes. |
| -m | Count characters. |
| -C | Same as -m. |
| -l | Count lines. |
| -w | Count words delimited by white space characters or new line characters. Delimiting characters are Extended Unix Code (EUC) characters from any code set defined by iswspace() |
| file | Name of file to word count. |
UNIX search and kill process on unix/linux box
kill $(ps -ef | grep tibco | grep tibemsadmin | grep EMS_QUERY_INFO_TMP | awk ‘{print $2}’)
Above will search for this command “ps -ef | grep tibco | grep tibemsadmin | grep EMS_QUERY_INFO_TMP”, and then kills the returned processes.
To do Telnet from one UNIX box to another
telnet host_name 3520
(It is to check if you are able to connect from current box to the remote box on a particular PORT )
Nslookup
nslookup is a network administration command-line tool available for many computer operating systems for querying the Domain Name System (DNS) to obtain domain name or IP address mapping or for any other specific DNS record.
The name nslookup means name server lookup. Nslookup uses the operating system’s local Domain Name System resolver library to perform its queries. Thus, it is configured automatically by the contents of the operating system file resolv.conf.[1]
Example:
nslookup host_name
nslookup host_name
PING Command
Use the ping command to test the connection between the local server and a remote UNIX server. The ping command sends ICMP Echo Request (ECHO_REQUEST) packets to the host once per second. Each packet that is echoed back via an ICMP Echo Response packet is written to the standard output, including round-trip time.
Syntax
ping serverName ping ServerIPAddress ping 192.168.1.2 ping yahoo.com ping server.cyberciti.biz
Netstat Command
To see which application is using which port, you can use this command.
netstat.exe –a –n –o. The switches we are using provide the following:
- -a: listing of all connections and listening ports
- -n: display address and port numbers in numerical form
- -o: display the owning PID associated with each connection
id Command
“id” will print the user ID and other details.
In Unix, how do I find a user’s UID or GID?
To find a user’s UID or GID in Unix, use the id command. To find a specific user’s UID, at the Unix prompt, enter:
id -u username
Replace username with the appropriate user’s username. To find a user’s GID, at the Unix prompt, enter:
id -g username
If you wish to find out all the groups a user belongs to, instead enter:
id -G username
If you wish to see the UID and all groups associated with a user, enter id without any options, as follows:
id username
Initialization files for each shell
| Shell | Profile File |
| Ksh | .profile |
| Bourne | .profile |
| Bash | .bash_profile |
| Tcsh | .login |
| Csh | .login |
LS command
Syntax :
ls [OPTION]… [FILE]…
Ls –ltr SHOW THE LAST MODIFEID AT THE END.
LS –a SHOW THE HIDDEN FILES.
Ls –ld */ SHOW ONLY THE DIRECTORIES.
Ls -1 list one file per line.
Ls –ld Gives information about the current directory (.)
-t sort by modification time
-r, reverse order while sorting
-l Long listing
-c, Use time of last modification of the i-node (file created, mode changed, and so forth) for sorting (-t) or printing (-l or -n).
-u Use time of last access instead of last modification for sorting (with the -t option) or printing (with the -l option).
ls – – color=auto (Recognizing the file type by the color in which it gets displayed is an another kind in classification of file)
-a, do not hide entries starting with.
-S do the sort by file size.
-X, Sort by extension
U, None or no sorting
version -v
status -c,
atime -u, access -u, use -u
Chmod
$ chmod -R 751 directory-name/ ——à Use option -R to change the permission recursively as shown below.
Type (File Type) ——– U (User) ————- G (Group) ———–O (Others)
– (normal file) rwx rwx rwx
L (Link file)
S (Socket file)
D (Directory)
Chown (change owner)
The chown command (abbreviation for change owner) is used on Unix-like systems to change the owner of a file. In most implementations,[citation needed] it can only be executed by thesuperuser, to prevent users simply changing ownership of files that aren’t their’s to access them. Unprivileged (regular) users who wish to change the group of a file that they own may use chgrp.
Syntax
chown [-R] newowner filenames
| -R | Change the permission on files that are in the subdirectories of the directory that you are currently in. |
| newowner | The alias/username of the new owner of the file. |
| filenames | The file that you are changing the rights to. |
Echo $SHELL —à This will give the shell name that you are using.
Folder Navigation on UNIX environments
| ~ | ——————————————à | Home Directory |
~ username —————————————————–à User name Home Directory
cd / ———————————————-à moves to root directory
cd .. ————————————–à Moves you one level up the directory tree structure
! ————————————————à Command History
Cd – ———————————————–à to toggle between the last two directories.
| $# | Number of arguments to script | |
| $* | Arguments to script | |
| $@ | Original arguments to script | |
| $- | Flags passed to shell | |
| $? | Status of previous command | |
| $$ | Process identification number | |
| $! | sh | PID of last background job |
$$ expands to the process id of the shell innovated to run the script. Useful for creating unique temporary filenames relative to this instantiation of the script.
You can use the “$$” to get the shell you are on, like this
Ps –p $$
In Unix you can set the Java PATH and JAVA CLASSPATH environment variables like below.
Q. How do I add new path to PATH variable under Linux and UNIX operating system?
A. The syntax for setting path under UNIX / Linux dependent on which shell you are using.
BASH / SH shell uses following syntax:
export PATH=$PATH:/path/to/dir1:/path/to/dir2
For tcsh or csh, shell enter:
set PATH = ($PATH /path/to/dir1 /path/to/dir2)
Example :
PATH=/opt/java/jdk1.6.0_22/bin:$PATH
export PATH
export CLASSPATH=.:/export/home/userID/JavaClient/*
(This will put all the jars in the folder JavaClient/* to the classpath)
df (disk free)
df displays the amount of disk space available on the file system containing each file name argument. If no file name is given, the space available on all currently mounted file systems is shown. Disk space is shown in 1K blocks by default, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
Report how much free disk space is available for each mount you have and the local file system.
This will display information about all the file systems (Both local and mounted)
EX : df -h
To get the information for a particular file system, mention the file system.
df –h (human readable format)
The above command is one of the most commonly used commands as it displays the sizes in an easy to read format as shown in the below example.
df –i (inode information)
list inode information instead of block usage
df –l (just show the local file system details, not the mounted disk details)
To know if the folder you are in is mounted or not.
du command (du – estimate file space usage)
Summarize disk usage of each FILE, recursively for directories.
Tells you how much space a file occupies.
du [-a] [-k] [-s] [-d] [-L] [-o] [-r] [-x] directories
ex : du –sh * (it will print the (size)sum of each folder or file in the current folder )
ex : du –sh . ( It will print the sum of the folder size)
-a Displays the space that each file is taking up.
-k Write the files sizes in units of 1024 bytes, rather than the default 512-byte units.
-s Instead of the default output, report only the total sum for each of the specified files.
-d Do not cross filesystem boundaries. For example, du -d / reports usage only on the root partition.
-L Process symbolic links by using the file or directory which the symbolic link references, rather than the link itself.
-o Do not add child directories’ usage to a parent’s total. Without this option, the usage listed for a particular directory is the space taken by the files in that directory, as well as the files in all directories beneath it. This option does nothing if -s is used.
-r Generate messages about directories that cannot be read, files that cannot be opened, and so forth, rather than being silent (the default).
-x When evaluating file sizes, evaluate only those files that have the same device as the file specified by the file operand.
Directories Specifies the directory or directories.
Special directories
| . | current directory, eg /home/kim/./ is /home/kim/, eg ls . is the same as ls |
| .. | parent directory, eg /home/kim/../ is /home, eg if you are in /home/kim ls .. will show you /home |
| .abc | files beginning with “.” are not show by default, use ls -a to see |
| / | paths starting with / are absolute, and do not depend on the current directory |
| ./foo | paths which do not start with / are relative, eg ../foo.py, or subdir/bar.py |
About pgrep and pkill
The pgrep utility examines the active processes on the system and reports the process IDs of the processes whose attributes match the criteria specified on the command line.
How To Use grep Command In Linux / UNIX
grep command searches the given file for lines containing a match to the given strings or words. By default, grep prints the matching lines. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines.
The name, “grep”, derives from the command used to perform a similar operation, using the Unix/Linux text editor ed:
g/re/p
grep command syntax
grep ‘word’ filename
grep ‘string1 string2’ filename
cat otherfile | grep ‘something’
command | grep ‘something’
$ grep boo /etc/passwd ——————à Search for boo in passed file.
$ grep -i “boo” /etc/passwd ————-à Case Sensitive search.
$ grep -r “192.168.1.5” /etc/ ———–à search recursively i.e. read all files under each directory for a string “192.168.1.5”
$ grep -w “boo” /path/to/file ———–à Exact word (When you search for boo, grep will match fooboo, boo123, etc. You can force grep to select only those lines containing matches that form whole words i.e. match only boo word 🙂
$ egrep -w ‘word1|word2’ /path/to/file –à It will return lines that matches word1 or word2.
$ grep -c ‘word’ /path/to/file ———-à grep can report the number of times that the pattern has been matched for each file using -c (count) option:
$ grep -n ‘word’ /path/to/file ———-à Line number (Also note that you can use -n option, which causes grep to precede each line of output with the number of the line in the text file from which it was obtained:)
$ grep -v bar /path/to/file ————-à (INVERT) Return lines that don’t match. You can use -v option to print inverts the match; that is, it matches only those lines that do not contain the given word. For example print all line that do not contain the word bar:
gzip / gunzip
These commands are used to zip or unzip the files.
Echo $SHELL ——à THIS WILL PRINT THE SHELL YOU ARE NO
(SHELL LEVEL)
Echo $SHLVL ——à TH IS WILL PRINT THE SHELL LEVEL YOU ARE ON.
You can do “exit” to go one shell up.
In normal cases the default SHELL is bash.
more Display a file, or program output one page at a time. Examples:
more mp3files.txt
ls -la | more
less An improved replacement for the “more” command. Allows you to scroll backwards as well as forwards. To search do “/search_string”. For the next pattern do “n”
su “Switch User”. Allows you to switch to another user’s account temporarily. The default account to switch to is the root/superuser account.
Examples:
su – Switch the root account
su – – Switch to root, and log in with root’s environment
su larry – Switch to Larry’s account
nohup command
| When working with the UNIX operating system, there will be times when you will want to run commands that are immune to log outs or unplanned login session terminations. This is especially true for UNIX system administrators. The UNIX command for handling this job is the nohup (no hangup) command.Normally when you log out, or your session terminates unexpectedly, the system will kill all processes you have started. Starting a command with nohup counters this by arranging for all stopped, running, and background jobs to ignore the SIGHUP signal.
The syntax for nohup is: |
| nohup command [arguments] |
| You may optionally add an ampersand to the end of the command line to run the job in the background: |
| nohup command [arguments] & |
| If you do not redirect output from a process kicked off with nohup, both standard output (stdout) and standard error (stderr) are sent to a file named nohup.out. This file will be created in $HOME (your home directory) if it cannot be created in the working directory. Real-time monitoring of what is being written to nohup.out can be accomplished with the “tail -f nohup.out” command.Although the nohup command is extremely valuable to UNIX system administrators, it is also a must-know tool for others who run lengthy or critical processes on UNIX systems. |
Unix Command Substitution (assign output of a command to the variable)
You need to use command substitution feature of bash. It allows you to run a shell command and store its output to a variable. To assign output of any shell command to variable in bash, use the following command
var=$(command-name-here)
var=$(command-name-here arg1)
var=$(/path/to/command)
var=$(/path/to/command arg1 arg2)
OR
var=`command-name-here`
var=`command-name-here arg1`
var=`/path/to/command`
var=`/path/to/command arg1 arg2`
Do not put any spaces after the equals sign and command must be on right side of =. See how to assign values to shell variables for more information.
Replace first letter of a string with different one
1) Replace 3 at the start of the string with 1,
_ssl_port_=$(echo ${_PORT_} | sed ‘s/^3/1/’)
2) Replace
Check if the string is starting with 3 or not
if [[ ${_PORT_:0:1} = “3” ]]
then
fi
tee command
Tee command is used to store and view (both at the same time) the output of any other command.
Tee command writes to the STDOUT, and to a file at a time as shown in the examples below.
The following command (with the help of tee command) writes the output both to the screen (stdout) and to the file.
$ ls | tee file
The following command will take a backup of the crontab entries, and pass the crontab entries as an input to sed command which will do the substituion. After the substitution, it will be added as a new cron job.
$ crontab -l | tee crontab-backup.txt | sed 's/old/new/' | crontab –
By default tee command overwrites the file. You can instruct tee command to append to the file using the option –a as shown below.
$ ls | tee –a file
You can also write the output to multiple files as shown below.
$ ls | tee file1 file2 file3
Syntax
tee [OPTION]… [FILE]…
| -a –append |
Append to the given FILEs, do not overwrite. |
| -i | ignore interrupt signals. |
| –help | Display the help screen. |
| –version | Display the version. |
Linux / UNIX source Command Examples
The source command in shell is used to execute commands from a file in the current shell. This is useful to load function or variables stored in another file.
source command syntax
The syntax is as follows:
source filename
source /path/to/file
It will read and execute commands from given FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME.
period-Linux Command (Dot)
source or dot operator
Syntax: “dot” command [period].
. filename [arguments]
source filename [arguments]
Description: Equivalent to source. This command, when invoked from the command-line, executes a script. Within a script, a source file-name loads the file file-name. Sourcing a file (dot-command) imports code into the script, appending to the script (same effect as the #include directive in a C program). The net result is the same as if the “sourced” lines of code were physically present in the body of the script. This is useful in situations when multiple scripts use a common data file or function library.
In Unix, how can I find the current values of all my environment variables and functions?
To find the current values of all your environment variables and functions in UNIX, if you are using the sh, ksh, or bash shell, at the prompt, enter:
set
If you are using the csh or tcsh shell, enter:
printenv
The resulting lists show all environment variables (e.g., home, shell) and functions, and their values, both default and user-defined. On most systems, entering setenv will display the same results as printenv.
For more information about the printenv or set commands, at the Unix prompt, enter either of the following commands:
man printenv
man set
Common environment variables in Unix
Most well-known environment variables are the following:
- USER – username of a Unix user
- HOME – full path to a user’s home directory
- TERM – terminal or terminal emulator used by a current user
- PATH – list of directories searched for executable files when you type a command in Unix shell
- PWD – current directory
Strings Checking
# Zero length Checking: [[ -z “$s1” ]]
# Nonzero length checking: [[ -n “$s1” ]]
Do “man test” to see all the string checking options
-d ———à to check if it is a directory or not.
Clear a File with /dev/null
Ways to clear a file.
1) > cat /dev/null > file_tobe_cleared.log
2) > cp /dev/null file_tobe_cleared.log
3) > > file_tobe_cleared.log
Redirection in UNIX (> and <)
command1 > file1
executes command1, placing the output in file1. This will clobber any existing data in file1.
command1 >> file1
To append output to the end of the file, use the >> operator:
command1 < file1
executes command1, with file1 as the source of input (as opposed to the keyboard).
|
Handle |
Name |
Description |
| 0 | stdin | Standard input |
| 1 | stdout | Standard output |
| 2 | stderr | Standard error |
command1 2> file1
executes command1, directing the standard error stream to file1.
Purpose of init.d folder
“/etc/Init.d/” folder contains the startup scripts, these scripts are invoked by the “init” process. “init” process will run the script “/etc/inittab/”, which will call processes in the folder “/etc/init.d/”.
Init
In Unix-based computer operating systems, init (short for initialization) is a daemon process that is the direct or indirect ancestor of all other processes. It automatically adopts all orphaned processes. Init is the first process started during booting, and is typically assigned PID number 1. It is started by the kernel using a hard-coded filename, and if the kernel is unable to start it, a kernel panic will result. Init continues running until the system is shut down.
Which
You can do this by using the which command, which will locate a command, if it exists, and tell you that it can’t locate it if it doesn’t. For example, to find out whether there are commands called dc and dac, type:
which dc which dac
Writing UNIX Scripts
(http://www.calpoly.edu/~rasplund/script.html)
There are actually no less than three different types of scripts supported in Unix: Bourne shell, C shell, and Korn shell. Bourne is the most common, Korn the most powerful, and C the most C-like (handy for C programmers). This tutorial will concentrate on the simplest of the three: the Bourne shell.
#!/bin/sh echo "hello world"
Comments and Commands
In the Bourne shell, any line beginning with a hash ‘#’ character in the first column is taken to be a comment and is ignored. The only exception is the first line in the file, where the comment is used to indicate which shell should be used (/bin/sh is the Bourne shell).
#!/bin/sh # purpose: print out current directory name and contents pwd ls
The special variables $1-$9 correspond to the arguments passed to the script when it is invoked.
Shell Variables
#!/bin/sh # name is a variable name="fred" echo "The name is $name"
Conditionals in Shell Scripts
#!/bin/sh
# show script
if [ -d $1 ]
then
ls $1
else
cat $1
fi
Here, we notice a number of points:
- The if-statement begins with the keyword if, and ends with the keyword fi (if, reversed).
- The if keyword is followed by a condition, which is enclosed in square brackets. In this case, the condition -d $1 may be read as: if $1 is a directory.
- The line after the if keyword contains the keyword then.
- Optionally, you may include an else keyword.
There are a number of conditions supported by shell scripts; for a complete list, use the on-line manual on the test command (man test). Some examples are: -d (is a directory?), -f (is a file?), = (are two strings the same?), -r (is string set?), -eq (are two numbers equal?), -gt (is first number greater than second?). You can also test whether a variable is set to anything, simply by enclosing it in quotes in the condition part of the if-statement. The script below gives an example:
Quoting in Scripts
Confusingly, in Shell scripts no less than three different types of quotes are used, all of which have special meanings. We have already met two of these, and will now consider all three in detail.
‘SAMPLE TEXT’ ————-à IT WILL BE TRATED AS LITERAL TEXT. SHELL WILL NOT LOOK FOR ANY COMMANDS OR VARIABLES INSIDE THE QUOTOS.
“SAMPLE TEXT” ————à IT WILL LOOK FOR VARIABLES INSIDE THE QUOTOS.
`SAMPLE TEXT` ————-à IT WILL INTERPRET THE TEXT INSIDE THE QUOTOS AS COMMAND.
` ` Command substitution ————————à
This quotation mark is the back quote (more properly called backtick or grave) character: “`”. It looks like the single quote and sometimes people get them confused in shell scripts. The first two are used for quoting phrases in UNIX. The back quote is not used for quoting characters. That character is used for command substitution, where the characters between them are executed by the shell and the results is inserted on that line. Example:
% echo the date is `date`
Let’s get back to the UNIX quoting mechanisms. The three quoting mechanisms you can use are the single quote, and double quote, and the b
‘ ’ —————-à Strong Quotes ———–à
Inside the single quotes, you can include almost all meta-characters:
% echo 'What the *heck* is a $ doing here???'What the *heck* is a $ doing here???
“ ” ———-à Weak Quotes ——-à
one that doesn’t expand meta-characters like “*” or “?,” but does expand variables and does command substitution. This can be done with the double quote characters:
% echo "Is your home directory $HOME?"Is your home directory /home/kreskin/u0/barnett?% echo "Your current directory is `pwd`"Your current directory is /home/kreskin/u0/barnett
Special shell variables
There are some variables which are set internally by the shell and which are available to the user:
$1 – $9 these variables are the positional parameters.
$0 the name of the command currently being executed.
$argv[20] refers to the 20th command line argument
$# the number of positional arguments given to this
invocation of the shell.
$? the exit status of the last command executed is
given as a decimal string. When a command
completes successfully, it returns the exit status
of 0 (zero), otherwise it returns a non-zero exit
status.
$$ the process number of this shell – useful for
including in filenames, to make them unique.
$! the process id of the last command run in
the background.
$- the current options supplied to this invocation
of the shell.
$* a string containing all the arguments to the
shell, starting at $1.
$@ same as above, except when quoted :
“$*” expanded into ONE long element : “$1 $2 $3”
“$@” expanded into THREE elements : “$1” “$2” “$3”
shift : $2 -> $1 …)
IF statement in UNIX scripting
If/Else
In order for a script to be very useful, you will need to be able to test the conditions of variables. Most programming and scripting languages have some sort of if/else expression and so does the bourne shell. Unlike most other languages, spaces are very important when using an if statement. Let’s do a simple script that will ask a user for a password before allowing him to continue. This is obviously not how you would implement such security in a real system, but it will make a good example of using if and else statements.
#!/bin/sh
# This is some secure program that uses security.
VALID_PASSWORD=”secret” #this is our password.
echo “Please enter the password:”
read PASSWORD
if [ “$PASSWORD” == “$VALID_PASSWORD” ]; then
echo “You have access!”
else
echo “ACCESS DENIED!”
fi
Remember that the spacing is very important in the if statement. Notice that the termination of the if statement is fi. You will need to use the fi statement to terminate an if whether or not use use an else as well. You can also replace the “==” with “!=” to test if the variables are NOT equal. There are other tokens that you can put in place of the “==” for other types of tests. The following table shows the different expressions allowed.
Comparisons:
| -eq | equal to |
| -ne | not equal to |
| -lt | less than |
| -le | less than or equal to |
| -gt | greater than |
| -ge | greater than or equal to |
File Operations:
| -s | file exists and is not empty |
| -f | file exists and is not a directory |
| -d | directory exists |
| -x | file is executable |
| -w | file is writable |
| -r | file is readable |
Check File Exists or Not
You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. The syntax is as follows:
test -e filename
[ -e filename ]
test -f filename
[ -f filename ]
It is possible to do wildcard style string comparisons in Bash scripting.
string=’My string’;
if [[ “$string” == *My* ]]
then
echo “It’s there!”;
fi
needle=’y s’
if [[ “$string” == *”$needle”* ]]; then
echo “haystack ‘$string’ contains needle ‘$needle'”
fi
Break Statement in Korn Shell Scripting
break ——————à it in break the flow from the enclosed loop.
break 2 —————à It will break the flow from the 2nd enclosed loop.
TAR and encrypt with openssl
# tar -cf – directory | openssl DHE-RSA-AES256-SHA -salt -out directory.tar.aes # Encrypt
Decrept with openssl and untar it
# openssl DHE-RSA-AES256-SHA -d -salt -in directory.tar.aes | tar -x -f – # Decrypt
Executing a background job
Appending an ampersand ( & ) to the command runs the job in the background.
Sending the current foreground job to the background using CTRL-Z and bg command
You can send an already running foreground job to background as explained below:
- Press ‘CTRL+Z’ which will suspend the current foreground job.
- Execute bg to make that command to execute in background.
View all the background jobs using jobs command
You can list out the background jobs with the command jobs. Sample output of jobs command is
Taking a job from the background to the foreground using fg command
You can bring a background job to the foreground using fg command. When executed without arguments, it will take the most recent background job to the foreground.
# fg
If you have multiple background ground jobs, and would want to bring a certain job to the foreground, execute jobs command which will show the job id and command.
In the following example, fg %1 will bring the job#1 (i.e download-file.sh) to the foreground.
# jobs [1] Running bash download-file.sh & [2]- Running evolution & [3]+ Done nautilus . # fg %1
Kill a specific background job using kill %
If you want to kill a specific background job use, kill %job-number. For example, to kill the job 2 use
# kill %2