Linux ksh if and

KSH IF Command Conditional Scripting Examples

H ow do I use if command with KSH to make decisions on Unix like operating systems?

KSH offers program flow control using if conditional command. if statement runs a set of command if some condition is true. For example, if directory /backup does not exists, create a new one so that your shell script can make backup to /backup directory.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements ksh
Est. reading time 10m

if statement has else part and it is get executed when condition is not satisfied or set to false state. This is also know as branching in ksh script.

KSH if statement syntax

The syntax is as follows:

Examples

IF the variable $x is greater to 0, THEN print out a message. Otherwise (else), print out a different message. Following shell script to read 2 numbers and find the greaters of the two:

Save and close the file. Run it as follows:
$ chmod +x script-name
$ ./script-name
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Find out if file /etc/passwd exists or not:

The -d option check for $DIR and make sure it is a directory. The -f option check for $FILE and make sure it is a regular file using conditional if command. The following script use if then elif then else fi syntax to display your OS name:

Run it as follows:
$ chmod +x find-os.ksh
$ ./find-os.ksh
Sample outputs:

See ksh(1) man page for more information.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Ksh Scripting

Principle of Script
Variables
Branching
Looping
Commandline Arguments
Comparisons
Variable Manipulations
Ksh Regular Expressions
Functions
Data Redirection
Pipes
Coprocesses
Read Input from User and from Files
Special Variables
Action on Success or Failure of a Command
Trivial Calculations
Numerical Calculations using «bc»
«grep»
«sed»
«awk»
«perl»

Principle of Script

Defining the Shell Type

To make a ksh script (which is a ksh program) crate a new file with a starting line like:
#!/usr/bin/ksh
It is important that the path to the ksh is propper and that the line doesn not have more than 32 characters. The shell from which you are starting the script will find this line and and hand the whole script over to to ksh. Without this line the script would be interpreted by the same typ of shell as the one, from which it was started. But since the syntax is different for all shells, it is necessary to define the shell with that line.

Four Types of Lines

A script has four types of lines: The shell defining line at the top, empty lines, commentary lines starting with a # and command lines. See the following top of a script as an example for these types of lines:

Start and End of Script

The script starts at the first line and ends either when it encounters an » exit » or the last line. All » # » lines are ignored.

Start and End of Command

A command starts with the first word on a line or if it’s the second command on a line with the first word after a» ; ‘.
A command ends either at the end of the line or whith a » ; «. So one can put several commands onto one line:

One can continue commands over more than one line with a » \ » immediately followed by a newline sign which is made be the return key:

Name and Permissions of Script File

The script mus not have a name which is identical to a unix command: So the script must NOT be called «test»!
After saveing the file give it the execute permissions with: chmod 700 filename .

Filling in

When filling into a variable then one uses just it’s name: state=»US» and no blanks. There is no difference between strings and numbers: price=50 .

Using

When using a variable one needs to put a $ sign in front of it: print $state $price .

Arrays

Set and use an array like:

arrname[1]=4 To fill in
print $ To print out
$ Get all elements
$ Get the number of elements

Declaration

There are happily no declarations of variables needed in ksh. One cannot have decimals only integers.

if then fi

if then else fi

if then elif then else fi

case esac

while do done

until do done

for var in list do done

continue. break

One can skip the rest of a loop and directly go to the next iteration with: » continue «.

One can also prematurely leave a loop with: » break «.

Command Line Arguments

(Officially they are called «positional parameters»)

The number of command line arguments is stored in $# so one can check
for arguments with:

The single Arguments are stored in $1, . $n and all are in $* as one string. The arguments cannot
directly be modified but one can reset the hole commandline for another part of the program.
If we need a first argument $first for the rest of the program we do:

One can iterate over the command line arguments with the help of the shift command. Shift indirectly removes the first argument.

One can also iterate with the for loop, the default with for is $* :

The program name is stored in $0 but it contains the path also!

To compare strings one uses » = » for equal and » != » for not equal.
To compare numbers one uses » -eq » for equal » -ne » for not equal as well as » -gt » for greater than
and «-lt» for less than.

With «&&» for «AND» and «||» for «OR» one can combine statements:

Removing something from a variable

Variables that contain a path can very easily be stripped of it: $ gives you just the filename.
Or if one wants the path: $ . % takes it away from the left and # from the right.
%% and ## take the longest possibility while % and # just take the shortest one.

Replacing a variable if it does not yet exits

If we wanted $foo or if not set 4 then: $ but it still remains unset. To change that we use:
$

Exiting and stating something if variable is not set

This is very important if our program relays on a certain vaiable: $

Just check for the variable

$ gives one if $foo is set, otherwise nothing.

Ksh Regular Expressions

Ksh has it’s own regular expressions.
Use an * for any string. So to get all the files ending it .c use *.c .
A single character is represented with a ? . So all the files starting with any sign followed bye 44.f can be fetched by: ?44.f .

Especially in ksh there are quantifiers for whole patterns:

?(pattern) matches zero or one times the pattern.
*(pattern) matches any time the pattern.
+(pattern) matches one or more time the pattern.
@(pattern) matches one time the pattern.
!(pattern) matches string without the pattern.

So one can question a string in a variable like: if [[ $var = fo@(?4*67).c ]];then .

Description

A function (= procedure) must be defined before it is called, because ksh is interpreted at run time.
It knows all the variables from the calling shell except the commandline arguments. But has it’s
own command line arguments so that one can call it with different values from different places in
the script. It has an exit status but cannot return a value like a c funcition can.

Making a Function

One can make one in either of the following two ways:

Calling the Function

To call it just put it’s name in the script: foo. To give it arguments do: foo arg1 arg2 .
The arguments are there in the form of $1. $n and $* for all at once like in the main code.
And the main $1 is not influenced bye the $1 of a particular function.

Return

The return statement exits the function imediately with the specified return value as an exit status.

General

Data redirection is done with the follwoing signs: » > >> «. Every program has at least a

standardinput, standardoutput and standarderroroutput. All of these can be redirected.

Command Output to File

For writing into a new file or for overwriting a file do: command > file

For appending to a file do: command >> file

Standard Error Redirection

To redirect the error output of a command do: command 2> file

To discard the error alltogether do: command 2>/dev/null

To put the error to the same location as the normal output do: command 2>&1

File into Command

If a program needs a file for input over standard input do: command

Combine Input and Output Redirection

command outfile
command outfile 2>/dev/null

Commands into Program ( Here Document )

Every unix command can take it’s commands from a text like listing with:

From eof to eof all is feeded into the above mentioned command.

For a serial processing of data from one command to the next do:
command1 | command2 | command3 .
e.g. last | awk ‘‘ | sort -u .

One can have one background process with which one can comunicate with read -p and print -p . It is started with command |& . If one uses: ksh |& then this shell in the background will do everything for us even telnet and so on: print -p «telnet hostname» .

Read Input from User and from Files

Read in a Variable

From a user we read with: read var . Then the users can type something in. One should first print something like: print -n «Enter your favorite haircolor: «;read var; print «» . The -n suppresses the newline sign.

Read into a File Line for Line

To get each line of a file into a variable iteratively do:

To catch the output of a pipeline each line at a time in a variable use:

$# Number of arguments on commandline.
$? Exit status of last command.
$$ Process id of current program.
$! Process id of last backgroundjob or background function.
$0 Program name including the path if started from another directory.
$1..n Commandline arguments, each at a time.
$* All commandline arguments in one string.

Action on Success or on Failure of a Command

If one wants to do a thing only if a command succeded then: command1 && command2 . If the second command has to be performed only if the first one failed, then: command1 || command2 .

Simpe calculations are done with either a «let» in front of it or within (( . )). One can increment a variable within the (( )) without a «$»: (( a+=1 )) or let a+=1 .

Numerical Calculations using «bc»

For bigger caluculations one uses «bc» like: $result=$(print «n=1;for(i=1;i

Search for the occurence of a pattern in a file: grep ‘pattern’ file . If one just wants to know how often soemthing occurs in a file, then: grep -c ‘pattern file . This can be used in a script like:
if [[ $(grep -c ‘pattern’ file) != 0 ]];then . ;fi . The condition is fullfilled if the pattern was found.

Sed means stream line editor. It searches like grep, but is then able to replace the found pattern. If you want to change all occurences of «poor» with «rich», do: sed -e ‘s/poor/rich/g’ filename . Or what is often seen in software packages, that have to be compiled after getting a propper configuration, is a whole file stuffed with replacements patterns like: /@foo@/s;;king;g . This file with inumerable lines like that has to be given to sed with: sed -f sedscript filename . It then precesses each line from file with all the sed commands in the sedscript. (Of course sed can do much more:-))

Awk can find and process a found line with several tools: It can branch, loop, read from files and also print out to files or to the screen, and it can do arithmetics.
For example: We have a file with lines like: Fred 300 45 70 but hundreds of them. But some lines have a «#» as the first sign of them and we have to omit these ones for both, processing and output. And we want to have lines as output like: 415 Fred where 415 is the sum of 300, 45 and 70. Then we call on awk:

This ignores lines with a «#» at the beginning of the first field and also blank lines. It then prints the desired sum and the $1 ist only printed after a tab. This is the most trivial use of awk only.

Perl is a much richer programming language then ksh, but still one can do perl commands from within a ksh script. This might touch Randal, but it’s true. Let’s say you want to remove all ^M from a file, then take perl for one line in your ksh script:

perl -i -ep ‘s/\015//g’ filename .

Perl can do an infinite amount of things in many different ways. For anything bigger use perl instead of a shell script.

Источник

What does if [[ $? -ne 0 ]]; mean in .ksh

I have a following piece of code that says if everything is executed mail a person if it fails mail the person with a error message.

I am new to linux coding I want to understand what if [[ $? -ne 0 ]]; means

4 Answers 4

Breaking it down, simple terms:

. signifies a test is being made for truthiness.

. is a variable holding the exit code of the last run command.

. checks that the thing on the left ( $? ) is «not equal» to «zero». In UNIX, a command that exits with zero succeeded, while an exit with any other value (1, 2, 3. up to 255) is a failure.

Is checking return code of immediately previous this if condition.

  • $? means return code
  • $? -ne 0 means previous command returned an error since 0 is considered success

If the previous command returned an error return code.

Presumably, the snippet is part of code that looks something like:

Which could (and should) be re-written more simply as:

The [[ $? -ne 0 ]] clause is a hackish way to check the return value of cmd , but it is almost always unnecessary to check $? explicitly. Code is nearly always cleaner if you let the shell do the check by invoking the command in the if clause.

Источник

Читайте также:  Не загружается windows только значок windows
Оцените статью