Bash Vs KSH

Bash Vs KSH

Linux and Unix have various shells. Two kinds of these numerous shells are KSH and BASH.

KSH (The Korn Shell) was developed many years before the BASH. Ksh has associative arrays and handles loop syntax better than bash. Also ksh’s command print is better than bash’s echo command. In other way, ksh does not support history completion, process substitution and rebindable command-line editing.

Bash has more added extension than ksh. Bash has tab completion and easier method to set a prompt in order to display current directory.

Compared to ksh, bash is newer and more popular.

Example of difference ksh and bash in condition test. First bash:

if [ $i -eq 3 ]

and condition test in ksh:

if (($i==3))

Bash can handle exit codes from pipes in a cleaner way. Bash and KSH are both Bourne=compatible shells, they share common functions and features and can be interchangeable to use.

Is ksh same as bash?

KSH and Bash shells are also products of combinations of other shells’ features. Bash and KSH are both Bourne-compatible shells. Since they share common features, they can be used interchangeably.

Is ksh faster than bash?

The ksh and zsh seems about seven times faster than bash . The ksh excelled in 17 tests and the zsh in six tests.

What is the difference between ksh CSH and bash?

CSH is C shell while BASH is Bourne Again shell. 2. C shell and BASH are both Unix and Linux shells. While CSH has its own features, BASH has incorporated the features of other shells including that of CSH with its own features which provides it with more features and makes it the most widely used command processor.

Is ksh a Linux shell?

Ksh is an acronym for KornSHell. It is a shell and programming language that executes commands read from a terminal or a file. It was developed by David Korn at AT&T Bell Laboratories in the early 1980s. It is backwards-compatible with the Bourne shell and includes many features of the C shell.

Why is ksh used?

ksh is a command and programming language that executes commands read from a terminal or a file. rksh is a restricted version of the command interpreter ksh; it is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell.

How do I run a ksh script in Bash?

How do I run . sh file shell script in Linux?

  • Open the Terminal application on Linux or Unix.
  • Create a new script file with .sh extension using a text editor.
  • Write the script file using nano script-name-here.sh.
  • Set execute permission on your script using chmod command : chmod +x script-name-here.sh.
    To run your script :

Is dash faster than Bash?

If you need speed, go definitely with dash, it is much faster than any other shell and about 4x faster than bash.

What is faster than Bash?

Perl is absurdly faster than Bash. And, for text manipulation, you can actually achieve better performances with Perl than with C, unless you take time to write complex algorithms.

How much faster is dash than Bash?

Dash is not Bash compatible, but Bash tries to be mostly compatible with POSIX, and thus Dash. Dash shines in: Speed of execution. Roughly 4x times faster than Bash and others.

What is difference between sh and ksh in Unix?

sh is the original Bourne shell. On many non-Linux systems, this is an old shell without the POSIX features. Thus bash and ksh (or even csh and tcsh) are better choices than sh. … Public domain ksh (pdksh) is Bourne-compatible and mostly POSIX-compatible.

Is zsh better than Bash?

It has many features like Bash but some features of Zsh make it better and improved than Bash, such as spelling correction, cd automation, better theme, and plugin support, etc. Linux users don’t need to install the Bash shell because it is installed by default with Linux distribution.

Bash How to Print Array

Bash How to Print Array

Arrays are collection of elements, The Arrays in bash are indexed from 0 (zero-based).
Below is the definition on an Array in Bash
my_array=(zero one two three four)

Now our array is defined.
Here is exactly how the my_array is stored on BASH:

my_array=([0]="zero" [1]="one" [2]="two" [3]="three" [4]="four")

You can explicit define an array:

declare -a MY_ARRAY

You can view the declarations along with other environment variables using the declare command.

declare -p my_array
declare -a my_array=([0]="zero" [1]="one" [2]="two" [3]="three" [4]="four")

Now if you try to print the array:

my_array=(zero one two three four)
echo $my_array
zero

By default only the first element value is printed which belongs to the 0 index.

To print the first element of the array using the indexing:

my_array=(zero one two three four)
echo ${my_array[0]}
zero

The change we noticed here is the use of the Curly Braces ‘{}’, its used to refer to the value of an item in the array. The curly braces are required to avoid issues with path name expansion.

To read all elements of the array use the symbols “@” or “*”.

echo ${my_array[@]}
zero one two three four
echo ${my_array[*]}
zero one two three four

The difference between “$@” and “$*” is “$@” expands each element as a separate argument, however “$*” expand to the arguments merged into one argument.

To prove this, print the index elements followed by $@ or $* format.

echo ${my_array[$*0]}
zero
echo ${my_array[$@1]}
one
echo ${my_array[$*2]}
two

Getting the Length of the Array

If you need to get the length of the array uses the symbol “#” before the name of the array:

echo "${#my_array[*]}"
5

How do I print an array in bash?

Print Bash Array

We can use the keyword ‘declare’ with a ‘-p’ option to print all the elements of a Bash Array with all the indexes and details. The syntax to print the Bash Array can be defined as: declare -p ARRAY_NAME.

How do I print in bash?

After typing in this program in your Bash file, you need to save it by pressing Ctrl +S and then close it. In this program, the echo command and the printf command is used to print the output on the console.

How do you print an array element in a new line in Shell?

To print each word on a new line, we need to use the keys “%s’\n”. ‘%s’ is to read the string till the end. At the same time, ‘\n’ moves the words to the next line. To display the content of the array, we will not use the “#” sign.

How do I display all array elements at once?

Program:
  1. public class PrintArray {
  2. public static void main(String[] args) {
  3. //Initialize array.
  4. int [] arr = new int [] {1, 2, 3, 4, 5};
  5. System. out. println(“Elements of given array: “);
  6. //Loop through the array by incrementing value of i.
  7. for (int i = 0; i < arr. length; i++) {
  8. System. out. print(arr[i] + ” “);

How do I create an array in bash?

  1. To declare your array, follow these steps:
    Give your array a name.
  2. Follow that variable name with an equal sign. The equal sign should not have any spaces around it.
  3. Enclose the array in parentheses (not brackets like in JavaScript)
  4. Type your strings using quotes, but with no commas between them.

How do you create an array in bash?

Define An Array in Bash

You have two ways to create a new array in bash script. The first one is to use declare command to define an Array. This command will define an associative array named test_array. In another way, you can simply create Array by assigning elements.

How does printf work in bash?

What Is the Bash printf Function? As the name suggests, printf is a function that prints formatted strings of text. That means you can write a string structure (the format) and later fill it in with values (the arguments). If you’re familiar with the C/C++ programming languages, you might already know how printf works.

How do you pass an array to a function in bash?

10 Answers

  1. Expanding an array without an index only gives the first element, use copyFiles “${array[@]}” instead of copyFiles $array.
  2. Use a she-bang #!/bin/bash.
  3. Use the correct function syntax. Valid variants are function copyFiles {… …
  4. Use the right syntax to get the array parameter arr=(“$@”) instead of arr=”$1″

How do you create an empty array in bash?

To declare an empty array, the simplest method is given here. It contains the keyword “declare” following a constant “-a” and the array name. The name of the array is assigned with empty parenthesis.

How do I get the size of an array in bash?

To get the length of an array, we can use the {#array[@]} syntax in bash. The # in the above syntax calculates the array size, without hash # it just returns all elements in the array.

Bash How to Read from Keyboard

Bash How to Read from Keyboard

To read input from the keyboard and assign input value to a variable use the read command.

Read syntax:

read options var1 var2

To write the value of first entered word use:

read var1 var2
echo $var1

If you don’t give any argument to the read command, input will assign to the environment variable REPLY.

The “s” option does not echo input while reading from a keyboard.

read -s -p "Enter password:" $password

The -p “TEXT” option displays TEXT to the user without a newline.

The -e option means that command readline is used to obtain the line.
Option -u FD reads inputs from file descriptor FD (0,1,2).
Option -t TIME causes that read returns a failure if the input is not read within TIME seconds.

Bash How to Return from Function

Bash How to Return from Function

Use the statement “return” to return from the function. You can also specify the return value. Example:

return 1234

We returned function status 1234 from function. Usually, we use 0 value for success and 1 for failure. It is similar to command exit which we use to terminate the script.

If you don’t use the return statement in the whole function, the status of the last executed command will be returned.

To verify returned status from the last called function use “$?”.

There is a difference between commands return and exit. The exit will cause the script to end at the line where it is called. Return will cause the current function to go out of scope and continue execution command after the function.

What is Bash Script

What is Bash Script

Metaphorically speaking bash script is like a ‘to-do list’. After you read the first entry you start realizing it. After you finished first entry, you continue with the second entry and so on.

A bash script is a text file that contains a mixture of commands.

Bash script can contain also functions, loops, conditional constructs. Scripts are commonly used for administration task like change file permission, creating disk backups. Using bash scripts is often faster than using the graphical user interface.

It’s important to mention that there is no difference between putting series of 10 commands into a script file and executing that script or you entering commands one by one to the command-line interface. In both situations, the result will be exactly the same thing.

After you create your script it is good practice to add the extension ‘.sh’ to the filename, for example ‘myFirstScript.sh’.

Bash Error Output Redirect

Bash Error Output Redirect

Each open file gets assigned a file descriptor. The file descriptors for STDIN is 0, for STDOUT is 1 nad STDERR is 2.

If you want to redirect just STDERR (standard error output) to file, ju do:

cmd_name 2> /file

If you want o redirect STDOUT to other files, and STDERR to other files, just do:

cmd_name >/stdout_file 2>/stderr_file

If you want to merge both (STDERR, STDOUT) into one file, you can do:

cmd_name >/file_4_both 2>&1

For the same effect, you can also use this syntax:

cmd_name &> /file_4_both

Even more, it is very useful to use the tee command. By definition, tee read from standard input and write to standard output and files, in same time.

In next example, we merge STDOUT and STDERR of “find /” command together. Then, we pass it to STDIN of tee command. Tee command is executed with -a parameter, that means append to an existing file (if exists):

find / 2>&1 | tee -a /home/tee.output
ll /home

Output: (lines omitted) -rw-r–r–. 1 root root 2.2M Jun 10 13:16 tee.output

The child process inherits open file descriptors. If you want to prevent file descriptors from being inherited, close it. For example:

<&-

This close stddin descriptor.

Bash How to do Math

Bash How to do Math

You can use arithmetic expansion with parentheses or square brackets:

a=0
echo $((a+5))

Output: 5

echo $[a+2]

Output: 2

Another option is using the command “bc”:

echo "5+3" | bc

Output: 8

If you need to do math with a float number, use the variable “scale” to define how operations use decimal numbers

echo "scale=2; 1/4" | bc

Output: 0.25

Evaluate expression with only integer you can use the command “expr”

echo `expr 10 - 2`

Output: 8

Be careful with multiply operations. Always escape * (asterisk) char with \. For example:

expr 5 \* 3

Output: 15

Bash How to Basename

Bash How to Basename

Command basename strip directory and suffix from filenames. Command syntax:

basename [option] name [suffix]

If the suffix is specified it will remove a trailing suffix. Example:

basename dir1/dir2/dir3/text_file.txt .txt

Output: text_file

Basename takes one argument (filename) and an optional suffix. If you want to give more file names use the option “a” which supports multiple arguments and threat each as “name”.

basename -a /dir/file.txt /dir2/picture.jpg

Output: file.txt picture.jpg

If you want to get the name of your home folder:

basename ~

Often used option is option -s which removes a trailing suffix. Here is an example:

basename -s .txt -a /dir/file.txt /dir2/picture.jpg

file picture.jpg

Bash Vs KSH

Bash Vs KSH

Linux and Unix have various shells. Two kinds of these numerous shells are KSH and BASH.

KSH (The Korn Shell) was developed many years before the BASH. Ksh has associative arrays and handles loop syntax better than bash. Also, ksh’s command print is better than bash’s echo command. In other way, ksh does not support history completion, process substitution, and rebindable command-line editing.

Bash has more added extension than ksh. Bash has tab completion and an easier method to set a prompt in order to display the current directory.

Compared to ksh, bash is newer and more popular.

Example of difference ksh and bash in condition test. First bash:

if [ $i -eq 3 ]

and condition test in ksh:

if (($i==3))

Bash can handle exit codes from pipes in a cleaner way. Bash and KSH are both Bourne=compatible shells, they share common functions and features and can be interchangeable to use.

Bash Scripting Best Practices

Bash Scripting Best Practices

Let’s begin with the first line of your script. The first rule always starts script with shebang. Without the shebang line, the system does not know which shell to process. For example:

#!/bin/bash

After shebang line write what is your script about and what it would do.

For debugging printout run your script with the “-x” or “-v” option like:

bash -x script.sh

Use the set lines:

set -e

set -u

set -o pipefail

“-e” to immediately exit if any command has non-zero exit status. “-u” causes the program to exit when you haven’t previously defined variable (except $* and $@). Option “-o pipefail” prevents fails in a pipeline from being masked. The exit status of the last command that threw non-zero exit code is returned.

Never use backticks, use:

$( ... )

Back-ticks are visually similar to single quotes, in a larger script with hundreds of lines you could be confused if it is back-ticks or single quotes.

If you need to create temporary files, use “mktemp” for temporary files and cleanup with “trap”.

Bash Hello World Script

Bash Hello World Script

This bash example creates an archive from /home directory to /backup/ directory as one tar.gz file. Let’s create a file backup.sh. It will consist of two lines:

#!/bin/bash
tar -czf /var/home-backup.tar.gz /home/

First line is a hashpling. Basically, it says who execute script. In this example, we choose /bin/bash.

The second line is tar command. It tarballs and compress the whole directory (/home) to one file.

I recommend you give also the third line (empty line). Why? If you execute this script in unusual UNIXes (ec. SCO UNIX), UNIX coudn’t execute last line, becasuse last symbol of file – EOF (end of file) is different from symbol EOLN (end of line). Symbol EOLN (enter) or semicolon (;) executes command.

Would you to extend this script to some output? Here is an example.

#!/bin/bash
echo -n Creating backup of home directory to /backup...
tar -czf /var/home-backup.tar.gz /home/ >/dev/null 2>&1
echo done.

On the second line, echo with n parameter doesn’t give a new line.

On the third line, output from tar command is redirected to trash (/dev/null).

Last line, just echoes done.

If you don’t know what to put on the first line (hashpling) type:

echo $SHELL

Output: /bin/bash

You will get path to your shell, which can use in the hashspling.