bash etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
bash etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

11 Kasım 2022 Cuma

bash arithmetic expansion

Giriş
Açıklaması şöyle. Yani bash sadece tam sayılar ile çalışır.
... Bash is only capable of handling integers, not floating point numbers, as explained in Arithmetic Expansion. If you try to sum floating point numbers, you will get the invalid arithmetic operator error.
Söz Dizimi
C=$((...))
Örnek - Hatalı Kod
Şöyle yaparız. Tam sayı olmadığı için hata alırız
#!/bin/bash
A='5'
B='6.4'
C=$(($A + $B))
echo $C
Bu gibi durumlarda bc komutunu kullanabiliriz. Şöyle yaparız.
#!/bin/bash
A='5'
B='6.4'
C=$(echo $A + $B | bc) 
echo $C

10 Mayıs 2022 Salı

bash kodlama - declare built-in komutu

-a seçeneği
Array veya Associative Array tanımlanır

-n seçeneği
name reference içindir. bash 4.3 ile geliyor.

Örnek
Şöyle yaparız
#!/bin/bash

declare -A num word

word=(
 [a]='index_a'
 [b]='index_b'
 [c]='index_c'
)

num=(
 [a]=1
 [b]=2
 [c]=3
)

declare -n var="$1"

printf '%s\n' "${var[@]}"
Çağırmak için şöyle yaparız
bash  array_call_self.sh  word



12 Ocak 2022 Çarşamba

bash kodlama - boolean logic

AND
Şöyle yaparız
if [[ -n $VAR_A ]] && [[ -n $VAR_B ]]; then
    echo >&2 "error: cannot use MODE B in MODE A"
    exit 1
fi

5 Ocak 2022 Çarşamba

bash kodlama command built-in komutu

Giriş
Görmek için şöyle yaparız
$ type command
command is a shell builtin
Açıklaması şöyle.
Essentially you would use command to bypass "normal function lookup". For example, say you had a function in your .bashrc:

function say_hello() {
   echo 'Hello!'
}
Normally, when you run say_hello in your terminal bash would find the function named say_hello in your .bashrc before it found, say, an application named say_hello. Using:

command say_hello  
makes bash bypass its normal function lookup and go straight to either builtins or your $PATH.
Yani kendi yazdığım bir bash metodu ile bir uygulamanın ismi çakışıyorsa, normalde bash benim metoduma öncelik verir. Bunu değiştirip uygulamayı çalıştırmak için "command foo" şeklinde çalıştırırız

bash Tilde Expansion

Giriş
Açıklaması şöyle
In short, ~ expands to $HOME, if $HOME is non-empty.

16 Aralık 2021 Perşembe

bash kodlama Positional Parameter için gömülü değişkenler

Giriş

Positional Parameter Salt Okunurdur
Açıklaması şöyle.
You can't assign to the positional parameters individually
$0 değişkeni - positional parameter
Örnek
Şöyle yaparız. Bize shell ismini gösterir. Mesela çıktı olarak "bash" yazar.
echo $0
Örnek - Yapmayın
Şöyle yaparız.  Mevcut shell için yeni bir shell daha başlatır.
$0
Açıklaması şöyle
As $0 contains the shell command that is running your shell script or interactive session; when you type $0 in a terminal, you are invoking the command name within the $0 argument variable.

When $0 contains bash; Typing $0 in the terminal, just runs bash. It then runs another bash within the scope of the first one, as a sub-shell.

As it runs another shell, it look like it did nothing, but started another shell session with same environment variables and settings. The shell prompt and current directory are exactly the same, so it look like nothing happened.

If you then try to close the terminal window, while a sub-shell has been invoked, it will tell you there are still background processes running.

What happens when you close the terminal window, is: It signals the first higher level shell Process ID to terminate, but this shell's PID know it has some child PID still attached, and just tells you about it.
$1 değişkeni - positional parameter
İki tane parametre alan basit bir metod için şöyle yaparız.
qh() {
  "$1" --help | grep -- "$2"
}
$9'dan sonra gelen değişkenler
$9'dan sonra gelen değişkenlere - örneğin 14. değişken olsun - $14 olarak erişemiyoruz. erişmek için ${X} şeklinde süslü parantez içine almak lazım. Açıklaması şöyle
The list of positional parameters can be as long as required and as current resource limits allows. This means that there may be well over 9 elements in the list. As you have already noticed, elements 10 and later may be accessed by adding braces around the number, as in ${12}.

Örnek
Elimizde şöyle bir script olsun. Bunu file isimli bir dosyaya kaydedelim
#! /bin/bash
echo $14
Daha sonra çalıştıralım. İstediğimiz 14 çıktısını alamayız
./file 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Doğru çıktıyı almak için şöyle yaparız
echo ${14}

21 Kasım 2021 Pazar

bash array - Array Expansion

Giriş
Array expansion veya tüm Diziyi Dolaşmak için "${myarr[@]}" veya "${myarr[*]}" kullanılır

Aralarındaki fark şöyle. Muhtemelen "${myarr[*]}" daha iyi.
If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word.
1. [@] Kullanımı
Örnek
Şöyle yaparız. Bir dosyadaki tüm satırları okuyup hepsini find komutuna geçeriz.
readarray -t a < pathlist.txt
find "${a[@]}" -type f ....
Örnek
Şöyle yaparız
declare data
data="pig,cow,horse,rattlesnake,"
declare -a my_array
IFS=',' read -r -a my_array <<< "$data"
for item in "${my_array[@]}"; do echo "$item"; done
Örnek
Şöyle yaparız
dirs=(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)

for dir in "${dirs[@]}"
do
 mkdir -p $dir
done
Örnek
Bir diğer seçenek olarak ${#array[@]} ile uzunluğunu alıp array[i] ile indeksine erişiriz. Şöyle yaparız.
for ((i=0 ; i < ${#array[@]} ; i++ )) ; do
    echo "${array[i]}"
done
2. [*] Kullanımı

Örnek

Şöyle yaparız. Kullanıcıdan sayı okunur. Daha sonra array değişkeni her bir elemanın etrafında boşluk karakteri olacak şekilde expand edilir. Daha sonra bu string içinde düzenli ifade kullanılarak arama yapılır
#!/bin/bash

array=( "one" "two" "three" "four" "five" )

function get_input() {
  read -p "${1}: " number
  if [[ " ${array[*]} " == *" ${number} "* ]]
  then
    echo 'true';
  else
    get_input 'Try again'   # a recursive call of the function
  fi
}

get_input 'Enter a number'  # the initial call of the function

30 Ekim 2021 Cumartesi

bash yönlendirme - redirection - Standard Output, Standard Error Birleştirme

Standard Output,  Standard Error Birleştirme Nedir
Açıklaması şöyle. Bu komut aslında bayağı karışık bir hal alabiliyor.
When you redirect something to &number, you are not opening a new file at all; you're reusing an already open file along with whatever mode it was opened.

The numbers refer to "open file" handles (file descriptors). So there is no technical difference between how >& and >>& (and indeed <&) would work – they all just mean "clone the existing file descriptor using dup()".

That is, 2>&1 indicates that file descriptor #1 (which you previously opened for appending using >>logfile) is cloned into number #2. And yes, 2<&1 works identically.
Bu yönlendirme POSIX uyumlu. Açıklaması şöyle.
So >out.txt 2>&1 is a POSIX-compliant way to redirect both standard output and standard error to out.txt.
Örnek
&>
veya
>&
şeklinde kullanılabilir. İlk kullanım tercih edilmeli. Şu kullanım ile aynıdır
>word 2>&1
1 - stdout
2 - stderr
akımlarıdır.

Bash'e özel
Bash'e özel şöyle yaparız
my_command_here arg1 arg2 |& less
Açıklaması şöyle
Note that |& is a Bashism. It does not work with /bin/sh (normally). If you want this in a portable shell script, use 2>&1 and a normal pipe instead.


Kullanım Örneleri
Klasik kullanımı daha kolay anlamak için birleştirme işlemlerini soldan başlayarak okumak lazım

Örnek
Klasik kullanım için şöyle yaparız. out.txt yeniden yaratılır ve hem stderr hem de stdout out.txt dosyasına yönlendirilir. Burada stderr çıktısı stdout'a yönlendiriliyor
my command > out.txt 2>&1  
Örnek - dev/null
Klasik kullanım için şöyle yaparız. Örnekte ise hem stdout hem de stderr /dev/null'a gönderiliyor. Böylece tüm çıktı /dev/null'a gönderilir. 
my command > /dev/null 2>&1  
Windows'ta /dev/null yerine sadece nul kullanılır.
your_dos_command 2> nul
Örnek - Biraz Karışık
Bu karışık kullanım C veya C++ dillerindeki pointer işlemlerine benziyor.  Eğer şöyle yaparsak, soldan okumaya başlarsak stderr önce stdout'a yönlendirilir, daha sonra stdout /dev/null'a gönderilir. Ancak stderr'i değiştirmedik. Yani halen stderr çıktısını ekranda görürüz.
command 2>&1 1>/dev/null
Benzer bir örnek şöyle
$ ( echo "this is stdout"; echo "this is stderr" >&2 ) 1>foo 2>&1 1>bar
$ cat foo
this is stderr
$ cat bar
this is stdout
Açıklaması şöyle
We can see that 2>&1 sends stderr to the "foo" file that stdout was redirected to, but when we redirect stdout to "bar" we don't alter stderr's destination. 

Örnek
Yönlendirmeyi kaldırmak için şöyle yaparız
exec 3>&-
Örnek
Şöyle yaparız. Burada stdout açıkça out.txt dosyasına yönlendiriliyor. stderr ise stdout'a yönlendiriliyor. Yani her şey out.txt dosyasına yazılıyor
my command 1 > out.txt 2>&1  
Örnek
Aynı şeyi şöyle yaparız.
my command &> out.txt
Örnek
Aynı şeyi şöyle yaparız.
my command 1>>out.txt 2>>out.txt
Örnek
Sadece bazı komutların çıktısını stdout'a diğerlerini /dev/null'a yönlendirmek için şöyle yaparız. exec bir bash built-in komutu
exec 3>&1 &>/dev/null
some_command
another_command
command_you_want_to_see >&3
command3
Açıklaması şöyle
You can use the exec command to redirect everything for the rest of the script.

You can use 3>&1 to save the old stdout stream on FD 3, so you can redirect output to that if you want to see the output.

28 Eylül 2021 Salı

bash kodlama $? gömülü değişkeni - Return Value

Giriş
Son çalıştırılan komutun exit status değerini verir.

Bu değişkeni Kullanmamak
Açıklaması şöyle
SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.
Bir uygulamayı çalıştırıp döndürdüğü sonucu almak için şu yol izlenebilir
utility

# shellcheck disable=SC2181
if [ "$?" -eq 0 ]; then
    echo ok
else
    echo fail
fi
Ancak şöyle yapmak daha kolay
if utility; then
    echo ok
else
    echo fail
fi
Kullanma Örnekleri
Örnek
Şöyle yaparız.
another_script.sh
exit_code=$?
Örnek
Şöyle yaparız.
grep -q '/example.com' /opt/nfs || grep -Rq '/example.com' /data
if [ $? -eq 0 ]; then   # check exit status
  echo "Passed"
else 
  echo "Failed"
fi
Örnek
set -e ile ilk hata da bash'in devam etmemesi sağlanır. Ancak bazı komutların 0'dan farklı bir şey dönmesi durumunda şöyle yaparız. Böylece set -e dikkate alınmaz.
#!/usr/bin/env bash
set -e
! docker stop foo
! docker rm -f foo
# ... other stuff