25 Aralık 2021 Cumartesi

readlink komutu

Giriş
Symbolic linkleri çözümlemek için kullanılır

-f seçeneği
Açıklaması şöyle
-f, --canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist
Örnek
awk komutu bir symbolic link olsun. Gerçekte nereye işaret ettiğini görmek için şöyle yaparız
$ readlink -f -- "$(which awk)"
/usr/bin/gawk

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}

9 Aralık 2021 Perşembe

SIGSEGV

Giriş
Açıklaması şöyle
The signal SIGSEGV is standardized but different OS might implement it differently. "Segmentation fault" is mainly a term used in *nix systems, Windows calls it "access violation".

6 Aralık 2021 Pazartesi

3 Aralık 2021 Cuma

/usr/lib Dizini

Giriş
/lib, /usr/lib, /var/lib dizinleri arasında fark var. Açıklaması şöyle. Yani /lib ve /usr/lib dizinleri salt okunur olarak kullanılmalı. /lib dizininde sisteme ait şeyler olur. /usr/lib dizininde kullanıcıya ait uygulamalar olur
Someone else can probably explain this with much more detail and historical reference but the short answer:
/lib
is a place for the essential standard libraries. Think of libraries required for your system to run. If something in /bin or /sbin needs a library that library is likely in /lib.

/usr/lib
the /usr directory in general is as it sounds, a user based directory. Here you will find things used by the users on the system. So if you install an application that needs libraries they might go to /usr/lib. If a binary in /usr/bin or /usr/sbin needs a library it will likely be in /usr/lib.

/var/lib
the /var directory is the writable counterpart to the /usr directory which is often required to be read-only. So /var/lib would have a similar purpose as /usr/lib but with the ability to write to them.

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

17 Kasım 2021 Çarşamba

kind - Yerel Kubernetes Cluster

Giriş
Açıklaması şöyle
Kind runs a local kubernetes cluster in Docker container and is an effective use to manage local kubernetes cluster deployment. The other alternative for local k8s cluster management is minikube...
create seçeneği
Örnek
Şöyle yaparız
kind create cluster --name local-dev
Örnek -- config
Elimizde şöyle bir yaml olsun
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
  extraPortMappings:
  - containerPort: 31234
    hostPort: 8080
    protocol: TCP
Şöyle yaparız
kind create cluster --name local-dev --config k8s-cluster-config.yaml
delete seçeneği
Örnek
Şöyle yaparız
kind delete cluster --name local-dev
get clusters seçeneği
Örnek
Şöyle yaparız
$kind get clusters
local-dev
get services seçeneği
Örnek
Şöyle yaparız
$kubectl get services

NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   5m53s

Kubernetes Operator

Giriş
Açıklaması şöyle. Custom Resource ve Custom Controller kavramı vardır
The basic idea of a Kubernetes Operator is to extend the Kubernetes’s level-driven reconciliation loop and API set towards running stateful application workloads natively on Kubernetes. A Kubernetes Operator consists of Kubernetes Custom Resource(s) / API(s) and Kubernetes Custom Controller(s)
Açıklaması şöyle
An Operator is packaged as a container image and is deployed in a Kubernetes cluster using Kubernetes YAMLs. 
Custom Resource Nedir?
Açıklaması şöyle
The Custom Resources represent an API that takes declarative inputs on the workload being abstracted and the Custom Controller implements corresponding actions on the workload. Kubernetes Operators are typically implemented in a standard programming language (Golang, Python, Java, etc.).
Açıklaması şöyle. Yani veri tabanı gibi şeyler Custom Resource oluyor
Once deployed, new Custom Resources (e.g. Mysql, Cassandra, etc.) are available to the end users similar to built-in Resources (e.g. Pod, Service, etc.). This allows them to orchestrate their application workflows more effectively leveraging additional Custom Resources.
Custom Resource, Kubernetes'e CRD metaPI kullanılarak tanıtılır. Açıklaması şöyle
In order for the Custom Resources to be recognized in a cluster, they need to be first registered in the cluster using Kubernetes’s meta API of ‘Custom Resource Definition (CRD)’. The CRD itself is a Kubernetes resource.
Helm ile kullanmak
Helm ile kullanmak için bazı maddeler şöyle
- Register Custom Resource Definitions in Helm chart (and not in Operator code)
- Make sure Custom Resource Definitions are getting installed prior to the Operator deployment
- Define Custom Resource validation rules in CRD YAML
- Use values.yaml or ConfigMaps for Operator configurables
- Add Platform-as-Code annotations to enable easy discovery and consumption of Operator’s Custom Resources
Örnek - Vitess
Şöyle yaparız
git clone git@github.com:vitessio/vitess.git
cd vitess/examples/operator

kubectl apply -f operator.yaml

15 Kasım 2021 Pazartesi

find komutu symbolic link arama seçenekleri

Giriş
Açıklaması şöyle
Some folders may contain symbolic links that link to another part of your file system. As such, you might unknowingly search a much larger set of folders, if symbolic links do exist. As such, there are a number of options that control what happens when find comes across a symbolic link:
  • -P - when used, symbolic links are never followed.
  • -L - when used, symbolic links are always followed.
  • -H - when used, symbolic links are only followed if mentioned somewhere on the command line, i.e. if you search for a link, and there is a symbolic link called link, find will return a link along with anything found when following that symbolic link.
Açıklaması şöyle
  -P     Never follow symbolic links.  This  is  the  default  behaviour.
          When find examines or prints information a file, and the file is
          a symbolic link, the information used shall be  taken  from  the
          properties of the symbolic link itself.

   -L     Follow symbolic links.  [...]

   -H     Do  not  follow symbolic links, except while processing the com‐
          mand line arguments.  When find examines or  prints  information
          about  files, the information used shall be taken from the prop‐
          erties of the symbolic link itself.  The only exception to  this
          behaviour is when a file specified on the command line is a sym‐
          bolic link, and the link can be resolved.  For  that  situation,
          the  information  used is taken from whatever the link points to
          (that is, the link is followed).  The information about the link
          itself  is used as a fallback if the file pointed to by the sym‐
          bolic link cannot be examined.  If -H is in effect  and  one  of
          the  paths specified on the command line is a symbolic link to a
          directory, the contents  of  that  directory  will  be  examined
          (though of course -maxdepth 0 would prevent this).
-H seçeneği
Şöyle yaparız. Ubuntu'da /bin artık symbolic link. Ancak komut satırından girince find komutu takip etsin istiyoruz.
find -H /bin -iname 'sh*'
Eğer -H seçeneğini kullamazsak şöyle yapınca bir sonuç alamayız
$ find /bin -iname 'sh*'

11 Kasım 2021 Perşembe

xinput komutu

Giriş
Farenin düğmesi tıklanınca başka bir düğme tıklanmış gibi yapmak veya etkinsizleştirmek için kullanılabilir.

set-button-map seçeneği
Örnek
Şöyle yaparız
Identify the ID/IDs of your device with

 xinput list 
Get the button map with

 xinput get-button-map <ID>
Set the button action

 xinput set-button-map <ID> 1 <new action>

Repeat the last command for as many IDs as your mouse has. 1 stands for the mapping of left-click, then for middle click, etc. Use for <new action> number 0 to disable middle-click, number 1 if you want to make it equivalent to left-click, etc.

10 Kasım 2021 Çarşamba

~/.ssh/known_hosts Dosyası

Giriş
İlk defa bağlantı kurulan bir ssh sunucusunun fingerprint (parmak izi) değeri bu dosyaya yazılır. Dosyanın içi şöyledir
myhost,1.2.3.4 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYT...YjdB=
Aynı sunucu için birden fazla satır olabilir ancak bu tavsiye edilmiyor. Açıklaması şöyle
It is permissible (but not recommended) to have several lines or different host keys for the same names.
Hashed Format
Dosyanın içindeki satırlar hashed formatta olabilir veya olmayabilir. Bu ayar ~/.ssh/config dosyasından kontrol ediliyor

7 Kasım 2021 Pazar

Kubernetes ConfigMap - Gizli Olmayan Veri

Giriş
ConfigMap içinde non-confidential yani gizli olmayan veri saklanır. Eğer gizli veri (password, token, key gibi) saklanacaksa Secret kullanılır

Pod içinde kullanırken
envFrom başlığı altında configMapRef şeklinde kullanılır
envFrom başlığı altında secretRef şeklinde kullanılır

Örnek
Şöyle yaparız
apiVersion: v1
kind: Pod
metadata:
  name: static-web
  labels:
    role: myrole
spec:
  containers:
  - name: nginx
    image: nginx
    envFrom:
    - configMapRef:
        name: testconfigmap
ConfigMap yaratmak
ConfigMap yaratmak için 2 tane yöntem var
1. ConfigMap yaml dosyası tanımlanır
2. Komut satırında "kubectl create configmap ..." yapılır

1. Dosya Tanımlama
kind olarak ConfigMap verilir ve data bölümünde key-value değerleri tanımlanır

Örnek
Şöyle yaparız
apiVersion: v1
kind: ConfigMap
metadata:
  name: mongodb
data:
  database-name: microservices
Örnek
Şöyle yaparız
apiVersion: v1
kind: ConfigMap
metadata:
  name: geared-marsupi-configmap
data:
  myvalue: "Hello World"
  drink: coffee
2. Komut Satırı
Örnek
configmap yaratmak için şöyle yaparız
#Create ConfigMap
kubectl create configmap testconfigmap --from-literal=TestKey1=TestValue1 
--from-literal=TestKey2=TestValue2 kubectl create configmap testconfigmap --from-file=/opt/test_file #Test kubectl get configmaps kubectl describe configmaps kubectl describe configmap testconfigmap
komut satırından kullanmak istersek iki seçenek var. Açıklaması şöyle
1. Use the contents of an entire directory with kubectl create configmap my-config --from-file=./my/dir/path/
2. Use the contents of a file or specific set of files with kubectl create configmap my-config --from-file=./my/file.txt

4 Kasım 2021 Perşembe

grep General Output Control - Dosya İsimleri veya Çıktıyı Kontrol Eder

Giriş
Çıktıyı kontrol etmek içindir.
--color
Açıklaması şöyle.
Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal.  ...  WHEN is neveralways or auto.
Varsayılan değer auto olduğu için şöyle yaparız.
grep --color ...
-L,--files-without-match
Açıklaması şöyle. Eşleşmeyen dosyaları verir
-L, --files-without-match

Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.

-l, --files-with-matches

Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
Örnek
Şöyle yaparız. Önce 'cat' kelimesini içeren dosyaların isimlerini alırız. Daha sonra bu dosyalarda 'dog' kelimesi içermeyenleri buluruz.
grep -L 'dog' $(grep -l 'cat' <list of files>)
-l,--files-with-matches
Açıklaması şöyle
grep -l lists the names of files with matching strings
Örnek
Şöyle yaparız. Bulunduğum dizin ve altındaki her şeyi tarar içinde abc geçen dosyaları listeler
grep -lRe abc .
-q, --quite, --silent
quite anlamına gelir. stdout'a çıktı yazmaz. If koşullarında kullanılır. Şöyle yaparız
if grep -q 'release 7\.[56] ' /etc/redhat-release
then ...
-o
Genellikle düzenli ifadeler ile kullanılır. Sadece eşleşen kısım gösterilir. Açıklaması şöyle
-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
Burada non-empty kısmı önemli çünkü bazen düzenli ifadeler ile boş string çıktısı gelebiliyor. Açıklaması şöyle
Many regular expressions can match empty text; for example:$ grep -E '.?' <<<""

outputs a blank line because the empty line matches. However, adding -o results in no output at all:$ grep -Eo '.?' <<<""

because -o ignores empty matches.

Specifying that -o ignores empty matches means the implementers don’t need to decide what to do with zero-length matches, which would otherwise produce rather lengthy (and useless) output in many circumstances.
Örnek
Şöyle yaparız.
$ str='25 results [22 valid, 2 invalid, 1 undefined]'
grep -E -o '[0-9]+' <<<"$str"