Sie sind auf Seite 1von 10

Unix Shell Script

-------------------------(1.) What is a UNIX shell?


The UNIX shell is a program that serves as the interface between the user and th
e UNIX operating system. It is not part of the kernel, but communicates directly
with the kernel. The shell translates the commands you type in to a format whic
h the computer can understand. It is essentially a command line interpreter.
List of commonly used UNIX shells:
- The Bourne Shell (sh)
- The C Shell (csh or tsch)
- The Bourne Again Shell (bash)
- The Korn Shell (ksh)
(2.) What needs to be done before you can run a shell script from the command li
ne prompt?
You need to make the shell script executable using the UNIX chmod command.
(3.) How do you terminate a shell script if statement?
With fi, which is "if" spelled backwards.
(4.) What UNIX operating system command would you use to display the shell's env
ironment variables?
Running the "env" command will display the shell environment variables.
Sample env command output:
$ env
HISTFILE=/home/lfl/.history
PATH=/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin
SHELL=/bin/ksh
HOSTNAME=livefirelabs.com
USER=lfl
MAIL=/var/spool/mail/lfl
HOME=/home/lfl
HISTSIZE=1000
--To get logged user:
$> echo $LOGNAME
--To get terminal:
$> echo $TERM
--To get Time Zone Information:
$> echo $TZ
(5.) What code would you use in a shell script to determine if a directory exist
s?
The UNIX test command with the -d option can be used to determine if a d
irectory exists.
Details:
The following test command expression would be used to verify the existe
nce of a specified directory, which is stored in the variable $mydir:
if [ -d $mydir ]

then
command(s)
fi
If the value stored in the variable mydir exists and is a directory file
, the command(s) located between then and fi will be executed.
(6.) How do you access command line arguments from within a shell script?
Arguments passed from the command line to a shell script can be accessed
within the shell script by using a $ (dollar sign) immediately followed with th
e argument's numeric position on the command line.
Details:
For example, $1 would be used within a script to access the first argume
nt passed from the command line, $2 the second, $3 the third and so on. Bonus: $
0 contains the name of the script itself.
(7.) How would you use AWK to extract the sixth field from a line of text contai
ning colon (:) delimited fields that is stored in a variable called passwd_line?
echo $passwd_line | awk -F: '{ print $6 }'
Details:
Consider this line of text stored in the variable $passwd_line $ echo $passwd_line
mail:x:8:12:mail:/var/spool/mail:
$
Here : is delimiter
(8.) What does 2>&1 mean and when is it typically used?
The 2>&1 is typically used when running a command with its standard outp
ut redirected to a file.
For example, consider:
command > file 2>&1
Anything that is sent to command's standard output will be redirected to
"file" in this example.
The 2 (from 2>&1) is the UNIX file descriptor used by standard error (st
derr). Therefore, 2>&1 causes the shell to send anything headed to standard erro
r to the same place messages to standard output (1) are sent...which is "file" i
n the above example.
To make this a little clearer, the > in between "command" and "file" in
the example is equivalent to 1>.
(9.) What are some ways to debug a shell script problem?
One method specific to shell scripting is using "set -x" to enable debug
ging.
Details:
Consider the following shell script example (notice that "set -x" is com
mented out at this time):

#!/bin/ksh
#set -x
i=1
while [ $i -lt 6 ]
do
print "in loop iteration: $i"
((i+=1))
done
exit
This script will produce the following output:
$ ./script1
in loop iteration:
in loop iteration:
in loop iteration:
in loop iteration:
in loop iteration:
$

1
2
3
4
5

If we uncomment (remove the #) from the "set -x" line in the script, thi
s is what is displayed when the script runs:
$ ./script1
+ i=1
+ [ 1 -lt 6 ]
+ print in loop iteration:
in loop iteration: 1
+ let i+=1
+ [ 2 -lt 6 ]
+ print in loop iteration:
in loop iteration: 2
+ let i+=1
+ [ 3 -lt 6 ]
+ print in loop iteration:
in loop iteration: 3
+ let i+=1
+ [ 4 -lt 6 ]
+ print in loop iteration:
in loop iteration: 4
+ let i+=1
+ [ 5 -lt 6 ]
+ print in loop iteration:
in loop iteration: 5
+ let i+=1
+ [ 6 -lt 6 ]
+ exit
$

Adding the Debugging Statement:


-------------------------------- To run an entire script in debug mode, add -x after the
#!/bin/ksh on the first line:
#!/bin/ksh -x

-- To run an entire script in debug mode from the


command line, add a -x to the ksh command used to
execute the script:
$ ksh -x script_name
-- To run debug with options, use -x, -v, or -f
Debug Mode Controls:
------------------1.) -x Displays the line after interpreting metacharacters and variables
2.) -v Displays the line before interpreting metacharacters and variable
s
3.) -f Disables file-name substitutions
4.) set -option Turns on the option
5.) set +option Turns off the option
(10.) Within a UNIX shell scripting loop construct, what is the difference betwe
en the break and continue?
Using break within a shell scripting loop construct will cause the entir
e loop to terminate. A continue will cause the current iteration to terminate, b
ut the loop will continue on the next iteration.
(11.) What you write on 1st line in a shell script?
#!/bin/ksh
(12.)How to connect to Oracle database from within shell script?
You will be using the same [sqlplus] command to connect to database that
you use normally even outside the shell script. To understand this, let's take
an example. In this example, we will connect to database, fire a query and get t
he output printed from the unix shell. Ok? Here we go
$>res=`sqlplus -s username/password@database_name <<EOF
SET HEAD OFF;
select count(*) from dual;
EXIT;
EOF`
$> echo $res
1
If you connect to database in this method, the advantage is, you will be
able to pass Unix side shell variables value to the database. See below example
$>res=`sqlplus -s username/password@database_name <<EOF
SET HEAD OFF;
select count(*) from student_table t where t.last_name=$1;
EXIT;
EOF`
$> echo $res
12
(13.)How to execute a database stored procedure from Shell script?
$> SqlReturnMsg=`sqlplus -s username/password@database<<EOF
BEGIN
Proc_Your_Procedure( your-input-parameters );
END;
/

EXIT;
EOF`
$> echo $SqlReturnMsg
(14.)How to fail a shell script programmatically?
Just put an [exit] command in the shell script with return value other t
han 0. This is because the exit codes of successful Unix programs is zero. So, s
uppose if you write
exit -1
inside your program, then your program will thrown an error and exit imm
ediately.
(15.)How to check if the last command was successful in Unix?
To check the status of last executed command in UNIX, you can check the
value of an inbuilt bash variable [$?].
See the below example:
$> echo $?
If it return 0 then last command is successful.
(16.)How to check if a file is present in a particular directory in Unix?
Using command, we can do it in many ways. Based on what we have learnt s
o far, we can make use of [ls] and [$?] command to do this.
See below:
$> ls l file.txt; echo $?
If the file exists, the [ls] command will be successful. Hence [echo $?]
will print 0. If the file does not exist, then [ls] command will fail and hence
[echo $?] will print 1.
(17.) Sample script to connect DB from UNIX & run PL/SQL
#!/bin/ksh
# ######################################################################
#####
# DESCRIPTION
# - Sample script to connect database from unix and run sql, pl/sql
# PARAMETER : empno
# ######################################################################
#####
#Path for Spool Log
SpoolLog=${BDR_SPL}/sample_script_db_`date '+%d-%m-%Y-%H-%M-%S`.log
in_empno=$1
echo "Empolyee Number Entered: "$in_empno
#SqlReturnMsg=`sqlplus -s username/password@database<<EOF`
sqlplus -s ${BDR_ORA_USR_OWN}/${BDR_ORA_PWD_OWN}<< EOF
WHENEVER SQLERROR EXIT FAILURE ROLLBACK;
WHENEVER OSERROR EXIT FAILURE ROLLBACK;
SET SERVEROUT ON SIZE 100000;

SET VER OFF;


SPOOL ${SpoolLog} append;
DECLARE
lv_empno
lv_ename
lv_sal
lv_deptno

emp.empno%TYPE;
emp.ename%TYPE;
emp.sal%TYPE;
emp.deptno%TYPE;

BEGIN
SELECT empno, ename, sal, deptno
INTO
lv_empno, lv_ename, lv_sal, lv_deptno
FROM emp
WHERE empno = ${in_empno};
DBMS_OUTPUT.PUT_LINE('empno: '||lv_empno||' ename: '||lv_ename||' sal: '
||lv_sal||' deptno: '||lv_deptno);
END;
/
SPOOL OFF;
EXIT;
EOF
error=`grep -i "error" ${SpoolLog}`
[ "A${error}" != "A" ] && exit 1
(18.)Special
-> $
-> ?
-> !

Shell Variables
Contains the process identification number of the current process
Contains the exit status of the most recent foreground process
Contains the process ID of the last background job started

-------------------------------Unix Command
-----------(1.) How to print/display the first line of a file?
$> head -1 file.txt
$> head -2 file.txt

--1st Line
--1st two Lines

(2.) How to print/display the last line of a file?


$> tail -1 file.txt
$> tail -2 file.txt

--1st Line from Last


--2 Lines from Last

(3.) How to display n-th line of a file?


$> head -<n> file.txt | tail -1
You need to replace <n> with the actual line number. So if you want to print the
4th line, the command will be
$> head -4 file.txt | tail -1
(4.) How to remove the first line / header from a file?

$> sed '1 d' file.txt


But the issue with the above command is, it just prints out all the line
s except the first line of the file on the standard output. It does not really c
hange the file in-place. So if you want to delete the first line from the file i
tself, you have two options.
Either you can redirect the output of the file to some other file and th
en rename it back to original file like below:
$> sed '1 d' file.txt > new_file.txt
$> mv new_file.txt file.txt
Or, you can use an inbuilt [sed] switch 'i' which changes the file in-pla
ce.
See below:
$> sed i '1 d' file.txt
(5.) How to remove the last line/ trailer from a file in Unix script?
Always remember that [sed] switch '$' refers to the last line. So using
this knowledge we can deduce the below command:
$> sed '$ d' file.txt > new_file.txt
$> mv new_file.txt file.txt
OR
$> sed i '$ d' file.txt
(6.)How to remove certain lines from a file in Unix?
If you want to remove line <m> to line <n> from a given file, you can ac
complish the task in the similar method shown above.
Here is an example:
$> sed '2,4 d' file.txt > new_file.txt
$> mv new_file.txt file.txt
$> sed i '2,4 d' file.txt
(7.)How to check the length of any line in a file?
$> sed n '<n> p' file.txt
Where <n> is to be replaced by the actual line number that you want to p
rint. Now once you know it, it is easy to print out the length of this line by u
sing [wc] command with '-c' switch.
$> sed n '35 p' file.txt | wc c
The above command will print the length of 35th line in the file.txt.
(8.) How to get the nth word of a line in Unix?
Assuming the words in the line are separated by space, we can use the [c
ut] command.
[cut] is a very powerful and useful command and it's real easy.
All you have to do to get the n-th word from the line is issue the follo
wing command:

cut f<n> -d' '


'-d' switch tells [cut] about what is the delimiter (or separator) in th
e file, which is space ' ' in this case.
If the separator was comma, we could have written -d',' then.
So, suppose I want find the 4th word from the below string: A quick brown
fox jumped over the lazy cat, we will do something like this:
$> echo "A quick brown fox jumped over the lazy cat" | cut -f4 -d' '
And it will print fox
(9.)How to reverse a string in unix?
Pretty easy. Use the [rev] command.
$> echo "unix" | rev
xinu
(10.) How to get the last word from a line in Unix file?
We will make use of two commands that we learnt above to solve this. T
he commands are [rev] and [cut].
Let's imagine the line is: C for Cat. We need Cat. First we reverse the line
. We get taC rof C. Then we cut the first word, we get 'taC'. And then we reverse
it again.
$>echo "C for Cat" | rev | cut -f1 -d' ' | rev
Cat
(11.)How to replace the n-th line in a file with a new line in Unix?
This can be done in two steps. The first step is to remove the n-th line
. And the second step is to insert a new line in n-th line position.
Step 1: remove the n-th line
$>sed -i'' '10 d' file.txt

# d stands for delete

Step 2: insert a new line at n-th line position


$>sed -i'' '10 i This is the new line' file.txt

# i stands for inser

t
(12.)How to show the non-printable characters in a file?
Open the file in VI editor. Go to VI command mode by pressing [Escape] a
nd then [:]. Then type [set list]. This will show you all the non-printable char
acters, e.g. Ctrl-M characters (^M) etc., in the file.
(13.)How to zip a file in Linux?
Use inbuilt [zip] command in Linux
$> zip file.txt
$> gzip file.txt
(14.)How to unzip a file in Linux?
Use inbuilt [unzip] command in Linux.
$> unzip j file.zip
$> gunzip file.gz

(15.)How to list down file/folder lists alphabetically?


Normally [ls lt] command lists down file/folder list sorted by modified t
ime.
If you want to list then alphabetically, then you should simply specify:
[ls l]
(16.)How to check all the running processes in Unix?
The standard command to see this is [ps]. But [ps] only shows you the sn
apshot of the processes at that instance. If you need to monitor the processes f
or a certain period of time and need to refresh the results in each interval, co
nsider using the [top] command.
$> ps -ef
If you wish to use this command inside some shell script, or if you want
to customize the output of [ps] command, you may use -o switch like below. By usi
ng -o switch, you can specify the columns that you want [ps] to print out.
$>ps -e -o stime,user,pid,args,%mem,%cpu
(17.)How to tell if my process is running in Unix?
$> ps -ef | grep "process_name"
(18.) Write command to list all the links from a directory?
ls -lrt | grep "^l"
(19.) Create a read-only
This is a simple
te a file and change its
lso change your umask to

file in your home directory?


UNIX command interview questions where you need to crea
parameter to read-only by using chmod command you can a
create read only file.

touch file
chmod 400 file
(20.) How will you find which operating system your system is running on in UNIX
?
By using command "uname -a" in UNIX
$>uname -a
SunOS gcrdevap01 5.10 Generic_147440-13 sun4u sparc SUNW,SPARC-Enterpris
e
(21.) How will you run a process in background? How will you bring that into for
eground and how will you kill that process?
For running a process in background use "&" in command line.
For bringing it back in foreground use command "fg jobid" and for gettin
g job id you use command "jobs", for killing that process find PID and use kill
-9 PID command.
This is indeed a good Unix Command interview questions because many of p
rogrammer not familiar with background process in UNIX.
(22.) How do you know if a remote host is alive or not?
You can check these by using either 'ping' or 'telnet' command in UNIX.
$>ping host_name
(23.) How do you see command line history in UNIX?
$> history

(24.) When an user logged in unix account, which startup script runs first?
- /etc/profile runs first when a user logs in.
- $HOME/.profile runs second when a user logs in.
- $HOME/.kshrc runs third if the ENV variable is set.
(25.) Which operator is used to combined unix command?
(26.) grep
-i
-c
-l
-v
-n

Options
Ignores uppercase and lowercase
Prints a count of lines that match
Prints the name of the files in which the lines match
Prints the lines that do not contain the search pattern
Prints the line numbers

Das könnte Ihnen auch gefallen