Tag Archives | Bash

Docker 18.06.0-ce duyuruldu

İşletim sistemi imajlarını versiyonlayan, Apache versiyon 2 lisanslı, Go dili ile yazılmış bir sanallaştırma ve konteyner teknolojisi olan Docker‘in 18.06.0-ce sürümü duyuruldu. Çeşitli hata düzeltmeleri ve iyileştirmelerle gelen yeni sürüm, gizlilik için Bash tamlanması içeriyor. Docker; kişilere ya da kuruluşlara çeşitli gereksinimlerini, çoklu problemlerini çözmelerine izin veren eksiksiz bir konteyner platformu sunuyor. Docker; BT liderlerinin mimarlık ve altyapı kilitlenmesi korkusu olmaksızın tüm uygulama portföylerini kendi hızlarıyla etkin bir maliyet ile oluşturup yönetebilecekleri bir ortam sağlayan, kurumsal kullanıma hazır bir konteyner platformudur. Docker ayrıca, yeni uygulamalar oluşturmak için zaman ve kaynak ayırma imkanı da sağlar. Bilindiği gibi Docker’in Community Edition (CE) ve Enterprise Edition (EE) olmak üzere iki sürümü bulunuyor. Yeni sürüm, bir Community Edition (CE) versiyonu. Docker 18.06.0-ce hakkında daha ayrıntılı bilgi edinmek için sürüm duyurusunu inceleyebilirsiniz.

Continue Reading →

Debian, Ubuntu gibi dağıtımlar için ayrı ayrı uygulamalar sunan Docker’in 8.06.0-ce sürümünü edinmek için aşağıdaki linklerden yararlanabilirsiniz.

0

Docker 18.05.0 duyuruldu

İşletim sistemi imajlarını versiyonlayan, Apache versiyon 2 lisanslı, Go dili ile yazılmış bir sanallaştırma ve konteyner teknolojisi olan Docker‘in 18.05.0 sürümü duyuruldu. Çeşitli hata düzeltmeleri ve iyileştirmelerle gelen yeni sürüme, gizlilik için Bash tamlanması eklenmiş bulunuyor. Docker; kişilere ya da kuruluşlara çeşitli gereksinimlerini, çoklu problemlerini çözmelerine izin veren eksiksiz bir konteyner platformu sunuyor. Docker; BT liderlerinin mimarlık ve altyapı kilitlenmesi korkusu olmaksızın tüm uygulama portföylerini kendi hızlarıyla etkin bir maliyet ile oluşturup yönetebilecekleri bir ortam sağlayan, kurumsal kullanıma hazır bir konteyner platformudur. Docker ayrıca, yeni uygulamalar oluşturmak için zaman ve kaynak ayırma imkanı da sağlar. Bilindiği gibi Docker’in Community Edition (CE) ve Enterprise Edition (EE) olmak üzere iki sürümü bulunuyor. Yeni sürüm, bir Community Edition (CE) versiyonu. Docker 18.05.0 hakkında daha ayrıntılı bilgi edinmek için sürüm duyurusunu inceleyebilirsiniz.

Continue Reading →

Docker 18.05.0 Debian, Ubuntu gibi dağıtımlar için ayrı ayrı uygulamalar sunan Docker’in 18.05.0 sürümünü edinmek için aşağıdaki linklerden yararlanabilirsiniz.

0

GNU GLOBAL 6.6.1 duyuruldu

Emacs ve Vi editörü, Bash kabuğu, çeşitli web tarayıcılar gibi değişik ortamlarda aynı şekilde çalışma becerisine sahip bir kaynak kod etiketleme sistemi olan GNU GLOBAL‘in 6.6.1 sürümü, Shigio YAMAGUCHI tarafından duyuruldu. Bunun bir hata düzeltme sürümü olduğunu söyleyen YAMAGUCHI; kritik bir güvenlik açığının giderildiğini ifade etti. İşlevler, makrolar, yapılar, sınıflar gibi çeşitli nesnelerin kaynak dosyalarına kolaylıkla yerleştirilebileceğini ve taşınabileceğini belirten YAMAGUCHI; GNU ve BSD gibi UNIX (POSIX) uyumlu işletim sistemlerinde uyumlu biçimde çalışan yazılımın, GNU Özgür Belgeleme Lisansı ile kullanıma sunulduğunu hatırlattı. C, C++, Yacc, Java, PHP4 ve assembly olmak üzere 6 dili destekleyen yazılım; makine mimarisinden bağımsız olan etiket dosyalarının artımlı güncellenmesini destekliyor. GNU GLOBAL 6.6.1 hakkında ayrıntılı bilgi edinmek için projenin sürüm duyurusunu inceleyebilirsiniz.

Continue Reading →

GNU GLOBAL 6.6.1 edinmek için aşağıdaki linklerden yararlanabilirsiniz.

0

GNU GLOBAL 6.6 duyuruldu

Emacs ve Vi editörü, Bash kabuğu, çeşitli web tarayıcılar gibi değişik ortamlarda aynı şekilde çalışma becerisine sahip bir kaynak kod etiketleme sistemi olan GNU GLOBAL‘in 6.6 sürümü, Shigio YAMAGUCHI tarafından duyuruldu. GNU GLOBAL 6.6’yı duyurmaktan büyük mutluluk duyduğunu söyleyen YAMAGUCHI; işlevler, makrolar, yapılar, sınıflar gibi çeşitli nesnelerin kaynak dosyalarına kolaylıkla yerleştirilebileceğini ve taşınabileceğini belirtti. GNU ve BSD gibi UNIX (POSIX) uyumlu işletim sistemlerinde uyumlu biçimde çalışan yazılım, GNU Özgür Belgeleme Lisansı ile kullanıma sunuluyor. C, C++, Yacc, Java, PHP4 ve assembly olmak üzere 6 dili destekleyen yazılım; makine mimarisinden bağımsız olan etiket dosyalarının artımlı güncellenmesini destekliyor. GNU GLOBAL 6.6 hakkında ayrıntılı bilgi edinmek için projenin sürüm duyurusunu inceleyebilirsiniz.

Continue Reading →

GNU GLOBAL 6.6 edinmek için aşağıdaki linklerden yararlanabilirsiniz.

0

Bash Scripting Part6 – Create and Use Bash Functions

Before we talk about bash functions, let’s discuss this situation. When writing bash scripts, you’ll find yourself that you are using the same code in multiple places. If you get tired of writing the same lines of code again and again in your bash script, it would be nice to write the block of code once and call it anywhere in your bash script. The bash shell allows you to do just that with Functions. Bash functions are blocks of code that you can reuse them anywhere in your code. Anytime you want to use this block of code in your script, you simply type the function name given to it. We are going to talk about how to create your own bash functions and how to use them in shell scripts.

Continue Reading →

Creating a function

You can create a function like this:

functionName {

}

Or like this:

functionName() {

}

The parenthesis on the second snippet is used to pass values to the function from outside of it, so these values can be used inside the function.

Using Functions

#!/bin/bash

function myfunc {

echo "Using functions"

}

total=1

while [ $total -le 3 ]

do

myfunc

total=$(( $total + 1 ))

done

echo "Loop finished"

myfunc

echo "End of the script"

Here we’ve created a function called myfunc and in order to call it, we just typed its name.

bash functions

The function can be called many times as you want.

Notice: If you try to use a function which is not defined, what will happen?

#!/bin/bash

total=1

while [ $total -le 3 ]

do

myfunc

total=$(( $total + 1 ))

done

echo "Loop End"

function myfunc {

echo "Using function ..."

}

echo "End of the script"

bash functions call before declare

Oh, it’s an error because there no such function.

Another notice: bash function name must be unique. Otherwise, the new function will cancel the old function without any errors.

#!/bin/bash

function myfunc {

echo "The first function definition"

}

myfunc

function myfunc {

echo "The second function definition"

}

myfunc

echo "End of the script"

bash functions override definition

As you can see, the second function definition takes control from the first one without any error so take care when defining functions.

Using the return Command

The return command returns an integer from the function.

There are two ways of using return command; the first way is like this:

#!/bin/bash

function myfunc {

read -p "Enter a value: " value

echo "adding value"

return $(( $value + 10 ))

}

myfunc

echo "The new value is $?"

bash functions return command

The myfunc function adds 10 to the  $value variable then show the sum using the $? Variable.

Don’t execute any commands before getting the value of the function, because the variable $? returns the status of the last line.

This return method returns integers. what about returning strings?

Using Function Output

The second way of returning a value from a bash function is command substitution. This way, you can return anything from the function.

#!/bin/bash

function myfunc {

read -p "Enter a value: " value

echo $(( $value + 10 ))

}

result=$( myfunc)

echo "The value is $result"

bash functions output

Passing Parameters

We can deal with bash functions like small snippets that can be reused and that’s OK, but we need to make the function like an engine, we give it something and it returns a result based on what we provide.

You can use the environment variables to process the passed parameters to the function. The function name is declared as $0 variable, and the passed parameters are $1, $2, $3, etc.

You can get the number of passed parameters to the function using the ($#) variable.

We pass parameters like this:

myfunc $val1 10 20

The following example shows how to use the ($#) variable:

#!/bin/bash

function addnum {

if [ $# -gt 2 ]

then

# If parameters no equal 2

echo "Incorrect parameters passed"

else

# Otherwise add them

echo $(( $1 + $2 ))

fi

}

echo -n "Adding 10 and 15: "

value=$(addnum 10 15)

echo $value

echo -n "Adding three numbers: "

value=$(addnum 10 15 20)

echo $value

bash functions pass parameters

The addnum function gets the passed parameters count. If greater than 2 passed, it returns -1.

If there’s one parameter, the addnum function adds this parameter twice. If 2 parameters passed, the addnum function adds them together, and if you try to add three parameters it will return -1.

If you try to use the passed parameters inside the function, it fails:

#!/bin/bash

function myfunc {

echo $(( $1 + $2 + $3 + $4))

}

if [ $# -eq 4 ]

then

value=$( myfunc)

echo "Total= $value"

else

echo "Passed parameters like this: myfunc a b c d"

fi

bash functions unknown parameters

Instead, you have to send them to the function like this:

#!/bin/bash

function myfunc {

echo $(( $1 + $2 + $3 + $4))

}

if [ $# -eq 4 ]

then

value=$(myfunc $1 $2 $3 $4)

echo "Total= $value"

else

echo "Passed parameters like this: myfunc a b c d"

fi

bash functions parameters

Now it works!!

Processing Variables in Bash Functions

Every variable we use has a scope, the scope is variable visibility to your script.

You can define two types of variables:

  • Global
  • Local

Global Variables

They are visible and valid anywhere in the bash script. You can even get its value from inside the function.

If you declare a global variable within a function, you can get its value from outside the function.

Any variable you declare is a global variable by default. If you define a variable outside the function, you call it inside the function without problems:

#!/bin/bash

function myfunc {

input=$(( $input + 10 ))

}

read -p "Enter a number: " input

myfunc

echo "The new value is: $input"

bash functions global variables

If you change the variable value inside the function, the value will be changed outside of the function.

So how to overcome something like this? Use local variables.

Local Variables

If you will use the variable inside the function only, you can declare it as a local variable using the local keyword  like this:

local tmp=$(( $val + 10 ))

So if you have two variables, one inside the function and the other is outside the function and they have the identical name, they won’t affect each other.

#!/bin/bash

function myfunc {

local tmp=$[ $val + 10 ]

echo "The Temp from inside function is $tmp"

}

tmp=4

myfunc

echo "The temp from outside is $tmp"

bash functions local variables

When you use the $tmp variable inside the myfunc function, it doesn’t change the value of the $tmp which is outside the function.

Passing Arrays As Parameters

What will happen if you pass an array as a parameter to a function:

#!/bin/bash

function myfunc {

echo "The parameters are: $@"

arr=$1

echo "The received array is ${arr[*]}"

}

my_arr=(5 10 15)

echo "The old array is: ${my_arr[*]}"

myfunc $my_arr

bash functions pass arrays

The function only takes the first value of the array variable.

You should disassemble the array into its single values, then use these values as function parameters. Finally, pack them into an array in the function like this:

#!/bin/bash

function myfunc {

local new_arr

new_arr=("$@")

echo "Updated value is: ${new_arr[*]}"

}

my_arr=(4 5 6)

echo "Old array is ${my_arr[*]}"

myfunc ${my_arr[*]}

bash functions pass arrays solution

The array variable was rebuilt thanks to the function.

Recursive Function

This feature enables the function to call itself from within the function itself.

The classic example of a recursive function is calculating factorials. To calculate the factorial of 3, use the following equation:

3! = 1 * 2 * 3

Instead, we can use the recursive function like this:

x! = x * (x-1)!

So to write the factorial function using bash scripting, it will be like this:

#!/bin/bash

function fac_func {

if [ $1 -eq 1 ]

then

echo 1

else

local tmp=$(( $1 - 1 ))

local res=$(fac_func $tmp)

echo $(( $res * $1 ))

fi

}

read -p "Enter value: " val

res=$(fac_func $val)

echo "The factorial of $val is: $res"

bash recursive function

Using recursive bash functions is so easy!

Creating Libraries

Now we know how to write functions and how to call them, but what if you want to use these bash functions or blocks of code on different bash script files without copying and pasting it on your files.

You can create a library for your functions and point to that library from any file as you need.

By using the source command, you can embed the library file script inside your shell script.

The source command has an alias which is the dot. To source a file in a shell script, write the following line:

. ./myscript

Let’s assume that we have a file called myfuncs that contains the following:

function addnum {

echo $(( $1 + $2 + $3 + $4))

}

Now, we will use it in another bash script file like this:

#!/bin/bash

. ./myfuncs

result=$(addnum 10 10 5 5)

echo "Total = $result"

bash functions source command

Awesome!! We’ve used the bash functions inside our bash script file, we can also use them in our shell directly.

Use Bash Functions From Command Line

Well, that is easy, if you read the previous post which was about the signals and jobs you will have an idea about how to source our functions file in the .bashrc file and hence we can use the functions directly from the bash shell. Cool

Edit the .bashrc file and add this line:

. /home/likegeeks/Desktop/myfuncs

Make sure you type the correct path.

Now the function is available for us to use in the command line directly:

$ addnum 10 20

bash functions use from shell

Note: you may need to logout and login to use the bash functions from the shell.

Another note: if you make your function name like any of the built-in commands you will overwrite the default command so you should take care of that.

I hope you like the post. Keep coming back.

Thank you.

likegeeks.com

0

Shell Scripting Part4 – Input, Output, and Redirection

In the previous post, we talked about parameters and options in detail, today we will talk about something very important in shell scripting which are Input, Output, and Redirection. You can display the output from your shell scripts in two ways:

  • Display output on the screen.
  • Send output to a file.

Everything is a file in Linux and that includes input and output.

Continue Reading →

Each process can have 9 file descriptors opened at the same time. The file descriptors 0, 1, 2 are kept for the bash shell usage.

0              STDIN.

1              STDOUT.

2              STDERR.

You can use the above file descriptors to control input and output.

You need to fully understand these three because they are like the backbones of your shell scripting. So we are going to describe every one of them in detail.

STDIN

STDIN stands for standard input which is the keyboard by default.

You can replace the STDIN which is the keyboard and replace it with a file by using the input redirect symbol (<), it sends the data as keyboard typing. No magic!!

When you type the cat command without anything, it accepts input from STDIN. Any line you type, the cat command prints that line to the screen.

STDOUT

This stands for the standard output which is the screen by default.

You can redirect output to a file using the >> symbol.

If we have a file contains data, you can append data to it using this symbol like this:

pwd >> myfile

The output generated by pwd is appended to myfile without deleting the existed content.

shell-scripting-append

The following command tries to redirect the output to a file using > symbol.

ls –l xfile > myfile

shell-scripting-redirect-error

I have no file called xfile on my PC, and that generates an error which is sent to STDERR.

STDERR

This file descriptor is the standard error output of the shell which is sent to the screen by default.

If you need to redirect the errors to a log file instead of sending it to the screen, you can redirect errors using the redirection symbol.

Redirecting Errors

We can redirect the errors by placing the file descriptor which is 2 before the redirection symbol like this:

ls -l xfile 2>myfile

cat ./myfile

shell-scripting-redirect-error-to-file

As you can see, the error now is in the file and nothing on the screen.

Redirecting Errors and Normal Output

To redirect errors and the normal output, you have to precede each with the proper file descriptor like this:

ls –l myfile xfile anotherfile 2> errorcontent 1> correctcontent

shell-scripting-redirect-error-and-data

The ls command result is sent to the correctcontent file using the 1> symbol. And error messages were sent to the errorcontent file using the 2> symbol.

You can redirect normal output and errors to the same file using &> symbol like this:

ls –l myfile xfile anotherfile &> content

shell-scripting-redirect-all-to-file

All errors and normal output are redirected to file named content.

Output Redirection

There are two ways for output redirection:

  • Temporarily redirection.
  • Permanently redirection.

Temporary Redirections

For temporary redirections, you can use the >&2 symbol like this:

#!/bin/bash

echo "Error message" >&2

echo "Normal message"

shell-scripting-temp-redirection

So if we run it, we will see both lines printed normally because as we know errors go to the screen by default.

You can redirect errors to a file like this:

./myscript 2> myfile

shell-scripting-redirect-error-to-file

Shell scripting is Awesome! Normal output is sent to the screen, while the echo message which has >&2 symbol sends errors to the file.

Permanent Redirections

If you have much data that need to be redirected, you can have a permanent redirection using the exec command like this:

#!/bin/bash

exec 1>outfile

echo "Permanent redirection"

echo "from a shell to a file."

echo "without redirecting every line"

shell-scripting-redirect-all-to-file

If we look at the file called outfile, we will see the output of the echo lines.

We redirect the STDOUT at the beginning, what about in the middle of a script like this:

#!/bin/bash

exec 2>myerror

echo "Script Begining ..."

echo "Redirecting Output"

exec 1>myfile

echo "Output goes to the myfile"

echo "Output goes to myerror file" >&2

shell-scripting-permenant-redirection

The exec command redirects all errors to the file myerror, and standard output is sent to the screen.

The statement exec 1>myfile is used to redirect output to the myfile file, and finally, errors go to myerror file using >&2 symbol.

Redirecting Input

You can redirect input to a file instead of STDIN using exec command like this:

exec 0< myfile

This command tells the shell to take the input from a file called myfile instead of STDIN and here is an example:

#!/bin/bash

exec 0< testfile

total=1

while read line

do

echo "#$total: $line"

total=$(( $total + 1 ))

done

shell-scripting-redirect-input

Shell scripting is easy.

You know how to use the read command to get user input. If you redirect the STDIN to a file, the read command will try to read from STDIN which points to the file.

Some Linux system administrators use this technique to read the log files for processing and we will discuss more ways to read the log on the upcoming posts in a professional way.

Creating Custom Redirection

You know that there are 9 file descriptors, you use only 3 of them for input, output, and error.

The remaining six file descriptors are available for use for input and output redirection.

The exec command is used to assign a file descriptor for output like this:

#!/bin/bash

exec 3>myfile

echo "This line appears on the screen"

echo "This line stored on myfile" >&3

echo "This line appears on the screen"

shell-scripting-create-redirection

Creating Input File Descriptors

To redirect input file descriptors do the following:

1-  Save the STDIN to another file descriptor.

2- Redirecting it to a file.

3- Revert STDIN to its original location.

Look at the following code to understand these steps:

#!/bin/bash

exec 7<&0

exec 0< myfile

total=1

while read line

do

echo "#$total: $line"

total=$(( $total + 1 ))

done

exec 0<&7

read -p "Finished? " res

case $res in

y) echo "Goodbye";;

n) echo "Sorry, this is the end.";;

esac

shell-scripting-create-input-file-descriptor

The STDIN is saved to file descriptor 7 and the STDIN is redirected to a file.

The STDIN reverted back to its original location after iterating over file lines.

The last read command just to make sure that STDIN is reverted back to and you can use the keyboard normally.

Close File Descriptors

The file descriptors are closed automatically when the script exits. If you want to close the file descriptor yourself, redirect the file descriptor to this symbol &- it will be closed.

#!/bin/bash

exec 3> myfile

echo "Testing ..." >&3

exec 3>&-

echo "Nothing works" >&3

shell-scripting-closing-file-desciptor

As you can see, it gives error bad file descriptor because it is no longer exist.

lsof Command

The lsof command is used to list all the opened files on the system and background processes.

On many Linux systems like Fedora, the lsof command is located under /usr/sbin.

This is some of the important options for lsof command:

-p: for process ID.

-d: for the file descriptor.

You can get the process PID using $$ variable.

shell-scripting-list-opened-desciptors

The -a is used to combine results of -p option and -d option.

Now, testing the command from a script:

#!/bin/bash

exec 4> myfile1

exec 5> myfile2

exec 6< myfile3

lsof -a -p $$ -d 0,1,2,4,5,6

shell-scripting-list-custom-descriptors

The shell script creates the file descriptors 4 and 5 for writing and 6 for reading.

Suppressing Command Output

Sometimes you don’t want to see any output. We redirect the output to the black hole which is /dev/null.

For example, we can suppress errors like this:

ls -al badfile anotherfile 2> /dev/null

And this idea is also used when you want to truncate a file without deleting it completely.

cat /dev/null > myfile

Now you understand the input, output, how to redirect them, how to create your own file descriptor, and redirect to it.

I hope you enjoy it. keep coming back.

Thank you.

likegeeks.com

0