16 Mayıs 2020 Cumartesi

bash kodlama - for döngüsü

Giriş
İmzası şöyle.
for name [ [in [words …] ] ; ] do commands; done
- Döngüde genellikle do komutu for komutu ile aynı satıra konulur.
- Veya do komutu kendi başına bir satıra konulur.
- Eğer do ile komutu aynı satıra koyarsak bence okuması daha zor kodlar ortaya çıkıyor.

do/Komut/done Hangi Satıra Konulmalı
Komutları kendi başına bir satıra koymak bence daha iyi. Açıklaması şöyle.
command list is a sequence of one or more simple commands separated or terminated by a newline or ; (semicolon). Furthermore, reserved words like do and done are normally preceded by a newline or ; ... In turn each time the command list following do is executed.
Örnek
Tek satır döngülerde şöyle yaparız.
$ for i in $(jot 2); do echo $i; done
Örnek
Şöyle yaparız. Ancak bence do ve komut aynı satırda olduğu için okuması zor.
for f in *
  do cmd1
  cmd2
done
Örnek
Şöyle yaparız. do komutu ayrı bir satırda
$ for i in $(jot 2)
> do
>     echo $i
> done
Break Nasıl Yapılır
Örnek - break
For döngüsünü öğrenirken sanırım en başta break; yapmayı öğrenmek gerekiyor. Şöyle yaparız.
for i in {1..10}; do
  sleep 10
  OUTPUT=$(systemctl is-active etcd)
  if [[ $OUTPUT == active ]]; then
    echo "The result is successful"
    break
  else
    echo "The result is unsuccessful"
  fi
done
Döngüde Kullanılabilen Aralık
1. {...} şeklinde sayı aralığı verilebilir. Aralık için değişken kullanılamaz
2. Değişken'in Değeri Kullanılabilir
3. seq komutuyla sayı aralığı üretilebilir.
4. uygulama çıktısı kullanılabilir
Örnek - sayı aralığı
Şöyle yaparız
for i in {0800..9999}; do
  for j in {001..032}; do
    wget http://site.com/"$i-$j".jpg
  done
done
Örnek - harf aralığı
Şöyle yaparız.
for d in {A..Z}; do 
  mkdir "$d"; 
  cd "$d"; 
done
Örnek - değişken
Şöyle yaparız.
for((i=1;i<=$rows;i++)); do
    echo "$RANDOM"
done
Örnek - array
Şöyle yaparız.
#! /bin/bash
servers=( 192.xxx.xxx.2 192.xxx.xxx.3
          192.xxx.xxx.4 192.xxx.xxx.5
          192.xxx.xxx.6 192.xxx.xxx.7
)

for server in "${servers[@]}" ; do
    echo "$server"
done
Örnek - uygulama çıktısı
Şöyle yaparız.
for node in `ls ~/sagLogs/`; do  
  foo &  
done
Örnek - seq
Şöyle yaparız.
for i in `seq 1 2000`; do
  mv file.$i.pdb file.pdb.$i
done
Örnek - seq
Şöyle yaparız.
for n in `seq 1 $count`
  do var=${numbers[0]}
done
Örnek - glob
glob'layarak dönmek için şöyle yaparız.
for globFile in lib/*.sh; do
  [ -f "$globFile" ] || continue
  source "$globFile"
done
Örnek - glob
data dizinin altında train ve test isimli iki dizin olsun. glob'layarak bu dizinlerdeki dosyaları saymak için şöyle yaparız. ${#files[@]} ile array'in uzunluğu alınır.
for dir in /data/*; do
  files=( "$dir"/*/* ); printf "%s\t%s\n" "$dir:" "${#files[@]}";
done
Çıktı olarak şunu alırız.
/data/test:     5432
/data/train:    1234
Örnek - yanlış glob
Bash pitfalls sayfasında find komutunun çıktısını döngü ile dolaşmak yanlış deniyor. Şu kod hatalı
for entry in `find . -type f`; do
  echo $entry 
done
Doğrusu find ve -print0'ı beraber kullanmak. Şöyle yaparız.
while IFS= read -r -d '' entry; do
  printf 'Processing: %s\n' "$entry"
done < <(find . -type f -print0 | sort -z)
Örnek - $@
Eğer for döngüsüne üzerinde yürüyeceği bir dizi vermezsek "positional parameters" üzerinde dolaşır. Şöyle yaparız.
#!/bin/bash
for var;
do
  echo "$var"
done
Çıktı olarak şunu alırız.
$ ./test a b c
a
b
c
Aslında şu kod ile aynı şeydir.
for i in "$@"; do
  something with "$i"
done

11 Mayıs 2020 Pazartesi

bash kodlama - gömülü değişkenler 2

Giriş
Bazı değişken isimleri BASH_XYZ şeklinde isimlendirilmiş. Bunlar tamamen bash'e mahsus.

BASHPID değişkeni
Açıklaması şöyle
Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset.
Örnek
Şöyle yaparız
printf '%s\n' "$BASHPID"
true | while true; do
    eval 'printf "%s\n" "$BASHPID"'
    break
done
BASH_SUBSHELL değişkeni
Açıklaması şöyle.
BASH_SUBSHELL
      Incremented by one within each subshell or subshell environment when the shell
      begins executing in that environment. The initial value is 0.
Örnek
Şöyle yaparız.
$ echo $BASH_SUBSHELL
0
$ (echo $BASH_SUBSHELL)
1
BASH_VERSINFO değişkeni
BASH_VERSINFO Değişkeni yazısına taşıdım.

SECONDS değişkeni
Açıklaması şöyle.
SECONDS
Each time this parameter is referenced, the number of seconds since shell invocation is returned.
Örnek
Şöyle yaparız
bash -c 'a=$SECONDS; sleep 5; b=$SECONDS; printf "%d seconds passed\n" "$((b-a))"'
Örnek
Bu değişkeni kendimiz değer atarsak beklenilen sonuç elde edilmez.Şu kod yanlış.
#!/bin/bash
SECONDS=5
i=1

while true
do
        echo "`date`: Loop $i"
        i=$(( $i+1 ))
        sleep $SECONDS
done

10 Mayıs 2020 Pazar

ps komutu

Giriş
process'ler hakkında bilgi verir. Açıklaması şöyle.
This version of ps accepts several kinds of options:

   1   UNIX options, which may be grouped and must be preceded by a dash.
   2   BSD options, which may be grouped and must not be used with a dash.
   3   GNU long options, which are preceded by two dashes.
Parametreler
Açıklaması şöyle. Ben parametrelere hep çizgi (-) ile başlıyorum
If we pass arguments with a (-) dash then we will get the output in standard syntax. In contrast, if we pass arguments without any (-) dash then we will get output in BSD (Berkeley Software Distribution) syntax.
En Çok Kullandıklarım
1. $ ps -efL
-e ile sahibi kim olursa olsun tüm processleri göster. 
-f ile full formatlama yap. Yani tüm sütunları göster
-L ile tüm thread'leri göster

2. ps aux
BSD formatında çıktı verir. Şöyle yaparız
$ ps aux | more
--------------------------------------------------------------------
USER  PID %CPU %MEM   VSZ   RSS  TTY   STAT START  TIME   COMMAND
root  1   0.6  0.5  169396 11312  ?    Ss   03:44   0:24  /sbin/init
root  2   0.0  0.0       0     0  ?    S    03:44   0:00  [kthreadd]
...
Açıklaması şöyle
%CPU CPU time used by this process (in percentage)

%MEM Physical memory used by this process (in percentage)

VSZ displays the amount of virtual memory being consumed by the process.

RSS is the actual physical wired-in memory that is being used.

START shows the date or time when the process was started.

TIME shows the total CPU time used by this process.

STAT displays the state of a process.
Process state tablosu şöyledir
D → Blocked
I → Blocked
R → Waiting or Running
S → Blocked
T → Blocked (more or less)
t → Blocked (more or less)
W → Blocked (obsolete since Linux 1.1.30)
X → Terminated
Z → Terminated
Simple Process Selection
Hangi process'lerin çıktıya dahil edileceğini belirtiriz. Genellikle "all processes" anlamına gelir
-a seçeneği
Açıklaması şöyle.
a = show processes for all users
Aslında -a seçeneği tüm process'leri göstermiyor. Açıklaması şöyle. Her şeyi görmek istiyorsak -e daha uygun
Select all processes except both session leaders (see getsid(2)) and processes not associated with a terminal.
Örnek
Şöyle yaparız.
ps -aux
-e seçeneği
Açıklaması şöyle.
e tells ps to display all processes regardless of who owns them or their current status – active, sleeping, paused, waiting for I/O, etc.
Açıklaması şöyle.
-e     Select all processes.  Identical to -A.
Örnek
Şöyle yaparız.
To see every process on the system using standard syntax:
      ps -e
      ps -ef
      ps -eF
      ps -ely

   To see every process on the system using BSD syntax:
      ps ax
      ps axu

   To print a process tree:
      ps -ejH
      ps axjf
-x seçeneği
Açıklaması şöyle. Arka planda çalışan uygulamaları da gösterir.
x = also show processes not attached to a terminal
Process Selection By List
Hangi process'lerin çıktıya dahil edileceğini belirtiriz.
- G seçeneği
Belirtilen gruba  ait processleri gösterir Şöyle yaparız
$ ps -G admin  # by group
-p seçeneği
Process ID'sine göre seçmek için kullanılır. Şöyle yaparız.
ps --ppid 2 -p 2 -o uname,pid,ppid,cmd,cls
-u seçeneği
Belirtilen kullanıcıya ait processleri gösterir Şöyle yaparız
$ ps -u root   # by username
Output Format Control
Eğer çıktı için hiç bir format belirtmezse çıktı şöyle
$ ps
--------------------------------------------------------------------
    PID TTY          TIME CMD
  54316 pts/0    00:00:00 bash
  54341 pts/0    00:00:00 ps
Bu sütunların açıklaması şöyle
PID — Unique process ID
TTY — Type of terminal that the user is currently logged in.
TIME — CPU time this process has consumed since it first started running. 
CMD — The command used to start the corresponding process.

-f seçeneği
Açıklaması şöyle.
-f     Do full-format listing. This option can be combined with many
          other UNIX-style options to add additional columns.  It also
          causes the command arguments to be printed.  When used with
          -L, the NLWP (number of threads) and LWP (thread ID) columns
          will be added.  See the c option, the format keyword args, and
          the format keyword comm.
Örnek
Şöyle yaparız. PGIS ile Process Group ID gösterilir.
$ ps -efj
UID          PID    PPID    PGID     SID  C STIME TTY      TIME CMD
root           1       0       1       1  0 11:18 ?        00:00:01 /usr/lib/systemd/systemd --switched-root --system --deserialize 18
root           2       0       0       0  0 11:18 ?        00:00:00 [kthreadd]
root           3       2       0       0  0 11:18 ?        00:00:00 [rcu_gp]
root           4       2       0       0  0 11:18 ?        00:00:00 [rcu_par_gp]
root           6       2       0       0  0 11:18 ?        00:00:00 [kworker/0:0H]
root           8       2       0       0  0 11:18 ?        00:00:00 [mm_percpu_wq]
root           9       2       0       0  0 11:18 ?        00:00:00 [ksoftirqd/0]
root          10       2       0       0  0 11:18 ?        00:00:00 [rcu_sched]
-j seçeneği
Açıklaması şöyle
List process in jobs format.
-o seçeneği
Sadece kullanıcı ismi istersek user şöyle yaparız.
$ ps axho user --sort -rss | head -1
Örnek
Kullancı bilgisini 16 karakter yapmak istersek şöyle yaparız
ps ax o user:16,pid,pcpu,pmem,vsz,rss,stat,start_time,time,cmd
-u seçeneği
Açıklaması şöyle. Uygulamanın sahibini ayrı bir sütunda gösterir.
u = display the process's user/owner
Şöyle yaparız.
$ ps aux | head -10
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  51120  2796 ?        Ss   Dec22   0:09 /usr/lib/systemd/...
root         2  0.0  0.0      0     0 ?        S    Dec22   0:00 [kthreadd]
root         3  0.0  0.0      0     0 ?        S    Dec22   0:04 [ksoftirqd/0]
root         5  0.0  0.0      0     0 ?        S<   Dec22   0:00 [kworker/0:0H]
root         7  0.0  0.0      0     0 ?        S    Dec22   0:15 [migration/0]
root         8  0.0  0.0      0     0 ?        S    Dec22   0:00 [rcu_bh]
root         9  0.0  0.0      0     0 ?        S    Dec22   2:47 [rcu_sched]
...
saml      3015  0.0  0.0 117756   596 pts/2    Ss   Dec22   0:00 bash
saml      3093  0.9  4.1 1539436 330796 ?      Sl   Dec22  70:16 /usr/lib64/..
saml      3873  0.0  0.1 1482432 8628 ?        Sl   Dec22   0:02 gvim -f
root      5675  0.0  0.0 124096   412 ?        Ss   Dec22   0:02 /usr/sbin/crond -n
root      5777  0.0  0.0  51132  1068 ?        Ss   Dec22   0:08 /usr/sbin/...
saml      5987  0.7  1.5 1237740 119876 ?      Sl   Dec26  14:05 /opt/google/chrome/...
root      6115  0.0  0.0      0     0 ?        S    Dec27   0:06 [kworker/0:2]
Output Modifiers
-h seçeneği
No header in output anlamına gelir.

-H seçeneği
Ağaç şeklinde gösterir. Şöyle yaparız. Burada sshd altında çalışan başka sshd process'leri görülebilir.
$ ps -ejH | grep sshd 
--------------------------------------------------------------------
    614     614     614 ?        00:00:00   sshd
  22310   22310   22310 ?        00:00:00     sshd
  30267   30267   30267 ?        00:00:00     sshd
  33871   33871   33871 ?        00:00:00     sshd
--sort seçeneği
rss'e göre sıralayabiliriz. Şöyle yaparız.
$ ps axho user --sort -rss | head -1
Şöyle yaparız.
 ps axho user,pid,rss --sort -rss | head -1
Thread Display
-L seçeneği
Örnek
Açıklaması şöyle.
L tells ps to show individual threads
the f tells ps to format the output as a full-format listing, and in conjunction with the L argument the NLWP (number of threads) and LWP (thread ID) columns are added to the output.
Şöyle yaparız.
ps -eLf

4 Mayıs 2020 Pazartesi

usermod komutu

Giriş
Açıklaması şöyle.
Remember to log out and log in again after running usermod, as it will not affect the groups of any existing process.
disk grubu
Açıklaması şöyle. Disk'e direkt okuma yazma hakkı verir.
Since the user can read any disk directly, the user would have access to files owned by any user on any disk.

The user would be able to not only read any disk, but would also be able to write directly to any block device file with the same permissions (g+rw). That user could easily corrupt any filesystem by accidentally writing to those block device files. Changing permissions to disallow the disk group write permissions might have other side effects that I can't predict.
sudo grubu
Örnek
gitlab-ci isimli kullanıcıyı sudo grubuna eklemek için şöyle yaparız
usermod -a -G sudo gitlab-ci
append seçeneği
Belirtilen gruba belirtilen kullanıcıyı ekler. Yani önce grup ismi daha sonra kullanıcı ismi gelir.
Örnek
Şöyle yaparız
# usermod --append --groups disk username
Örnek
Şöyle yaparız.
usermod --append --groups mygroup myuser
İşlemden sonra sisteme tekrar giriş yapmak gerekir. Kullanıcının gruba dahil olduğunu id komutu veya groups komutu ile görebiliriz.

Örnek
user2'nin olduğu gruba user'i de eklemek için şöyle yaparız.
usermod -a -G user2 user1
-d seçeneği
Kullanıcı home dizini şöyle değiştirilir
usermod -d /home/newHomeDir -m newUsername
-G seçeneği
Grup ismini belirtir.

Örnek
Kendi kullanıcımı debian-transmission kullanıcısının grubuna eklemek için şöyle yaparız.
sudo usermod -a -G debian-transmission "$USER"
-l seçeneği - login name
Belirtilen kullanıcının login adını değiştirir. Şöyle yaparız.
usermod -l newUsername oldUsername

swapon komutu - Swap Dosyası

Giriş
Not mkswap komutu ve swapoff komutu yazılarına da bakabilirsiniz.

swap Zaralı mıdır?
Açıklaması şöyle. swap bazen istenmeyebilir.
Swap can be bad in that it may make some failure cases last longer. Consider a situation where some process starts using excessive amounts of memory, due to a bug or a misconfiguration or other such reason. If there's no swap, it'll eventually run the system out of memory, causing the OS to resolve the issue by eventually killing the process. (But possibly causing other trouble anyway.)

But if there is loads of swap space, the process will start consuming swap space, possibly thrashing pages between main memory and swap, and that slows eve-ry-thing down. The system will eventually run out of memory, but you suffer longer before that.
swapfile vs swap partition
swap için genellikle ya bu işe adanmış bir partition (bölümleme) veya bu işe adanmış dosya kullanılır
Açıklaması şöyle
Technically, a swap partition is more efficient than a swap file. Practically, if the swap file is contiguous, there should not be a lot of difference, and current versions of linux, no performance difference at all. There are a few bugs around swap files, but they are only triggered in some odd circumstances.
Eğer swap partition kullanılıyorsa, bu partition için gerçek bir dosya sistemi bulunmaz.

Ubuntu
Ubuntu /swapfile dosyasını kullanır. Açıklaması şöyle
Since 18.04, a separate swap partition has been superseded by a swapfile within the root partition. A separate swap partition is no longer recommended for most new users.

swapon Komutu
Swap dosyasını etkinleştirmek için için şöyle yaparız.
sudo swapon /swapfile
-a seçeneği
Swap olarak tanımlanan tüm dosyaları etkinleştirir. Şöyle yaparız.
swapon -a
-s seçeneği
swap dosyasını ve büyüklüğünü görmek için şöyle yaparız. Benim sistemimde swap dosyası /dev/sda3 olarak görünüyor ve büyüklüğü 5G
$ sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        1048572 736640  -1
$ ls -lh /swapfile
-rw------- 1 root root 1.0G Nov  9  2016 /swapfile

reboot komutu

Giriş
Açıklaması şöyle. Çalışan uygulamalara önce SIGTERM gönderir. Uygulama hala kapanmadıysa SIGKILL gönderir. Kaydedilmeyen veriler kaybolabilir.
The halt and reboot utilities flush the file system cache to disk, send all running processes a SIGTERM (and subsequently a SIGKILL) and, respectively, halt or restart the system.
Kullanım
Ubuntu 14.10 ve daha eski sürümlerde
sudo reboot
şeklinde kullanılır. Daha yeni sürümlerde eğer sisteme giriş yapmış tek kullanıcı varsa sadece
reboot
yapmak yeterli. Birden fazla kullanıcı varsa yine eskisi gibi
sudo reboot
yapmak gerekiyor.Bu kadar şeyi hatırlamamak için hep sudo reboot yapmak daha iyi.

Diğer
Bu komutun kardeşi shutdown komutu