Category: Linux CLI

  • Hetzner vs Digital Ocean in 2022

    Hetzner vs Digital Ocean in 2022

    Hetzner aka the mail server not hosting. Hetzner blocks mail server ports 24 and 465 incoming and outgoing but allows port 587. You could make a mail server work on Hetzner Cloud hosting.

    Asked on reddit hetzner vs digital ocean in 2022.

    Now on Digitalocean, looking for a cheaper option after they increased the prices.
    Heard about Hetzner before but didn’t go with it.
    It looked more like the old style of shared cpanel hosting.

    Lowest Droplet vs Lowest Hetzner cloud?
    Anyone made the move and is happy or not?
    Hezner cloud means VPS yeah? Like a do droplet.

    Thinking of relative performance overall, sites response time.

    My concerns before moving

    Can you fund your account with a set amount and then they lower the balance? Or you must pay hosting cost every month (manual or automatic). Turns out yes you can by bank transfer – old school.

    Saw PayPal there but also a 20 EUR load amount to verify identity so didn’t touch that!

    Cpx11 was looking good 2 vcpu, 2gb ram 40gb disk space. Nice.

    Another concern

    It’s a hassle to move but already did a migration from one do vps to another.

    I’d like to think this time would be better.

    Does Hetzner allow emails or to listen on any port? I know people hate that but it’s not for spam and mostly to send to our own email as alerts / notifications.

    Answer is no, talk to support it’s fast.

    Interesting, I bet it will take a week if I do it haha (will be months…if I stay).
    Edit: I was hoping there is some kind of firewall settings but if it’s granted fast it should be ok.

    Asked, they said no emails until 1 month or 1 invoice or something about building trust like they have to trust me not their devops infrastructure and security.

    Cloud Protection

    I’ve read if you get ddos’d they could actually kill your server and account.

    Someone starting a DDOS would be so happy they caused their target’s termination.

    Moving from Digital Ocean to Hetzner

    So I migrated today, rushed but wanted it done.

    Nice specs on 4.75 euro cpx11, 2gb ram, 2 vcpu but.

    In reality, it’s the same performane (wordpress +db page speed) as digitalocean 1gb ram, 1 vcpu.
    Strange, maybe under a stress load, there would be some difference.

    Emails problem on Hetzner

    I open a ticket to allow email ports, got rejected. Account too young and not 1 invoice paid yet…
    Later i can request limits increase but they might still reject it.
    I’ll see about emails maybe start tls instead of ssl would work. It didn’t for outbound emails.

    Support

    They are very fast to say no.

    Server startup was fast no problems there.

    Now my gmail keeps asking for credential because of Hetzners paranoid email port policy.

    The biggest problem with Hetzner is speed

    Made a backup after got it setup, ftp dowload to local pc, 10 mbps max 14 mbps. Digital ocean was reaching full speed of my home connection 100MBps.

    This was more of a way to verify the migration scripts.

    Btw, you can spinup 5 servers max and lookup the ipv4 they give you for spam db reports just in case.

    Lots of their ips are listed allover spam databases anyway.

    I chose the one with least reports.

    Still looking for a good $5 hosting.

    My Hetzner story

    Update after migration, feeling the Hezner cpx11 server. Not bad but not great.

    Other than the email SMTP blockage story with support messages not actually reading my message and replying with templates.
    It’s a good service so far.

    This website is at this time 12 July 2022 hosted on Hetzner coupled with Cloudflare CDN.

    Got the low cost but juicy AMD Epyc cpx11 with 2vcpu and 2gb ram.
    More resources for less money on paper. In practice it’s very similar for low volume traffic.

    Websites use Cloudflare CDN so for me speed from Cloudflare to Hezner Ashburn, Virginia US is OK.

    Website load time without Cloudflare CDN – DNS Pass-thru is actually the same as DigitalOcean $6 1vcpu 1gb ram so that’s strange but under stress it would show some difference hopefully.

    it looks nice in htop, all migrated in 1 day.

    Migration scripts improved so next time it’s easier.

    I don’t need super good uptime but if the server is down and I see it down and it’s a whole day, I would move asap. For me no problems like this so far, all up and running.

    Speaking of moving I don’t trust them. Even less than DigitalOcean. But I trust Hezner more than AWS to not sneak some funky extra charges.

    All ok, nothing too crazy except a strange out bandwidth problem.
    Copying a backup out from the server was going slow at 3mbps while DigitalOcean was full speed of my home ISP 100mbps.

    The slow speed happens on regular Filezilla Client connecting to the server thru ssh on a custom ssh port 4 digits. It might aswell be that Hetzner is rate limiting custom ports? this would be the cherry on the Hezner Cloud hosting cake. No they say no port speed limiting.

    Try it with your server. For me similar location is US, was full ISP speed, now it’s ADSL speed equivalent transfer.

    If they can give good reasons for blocking smtp, rate limiting ports is another story. Unless it’s just their server network being slow, yesterday and today.

    SSH transfer speed from Hetzner server

    Hetzner network transter slow
    Hetzner network transter slow

    Dowload speed from the server to local Filezilla client won’t exceed 1.5 Mib/s now 1.6Mib/s

    Hetzner network transfer rate limiting 1 6
    Hetzner network transfer rate limiting 1.6 MiB/S

    Transfer time approx. 5 minutes for a approx. 500 MB file.

    Hetzner network transfer rate limiting
    Is Hetzner network transfer rate limiting?

    Fast.com speed test on home network.

    fastdotcom speed test
    fastdotcom speed test

    What do you think?

    Sent support question 12-07-2022

    I download a tar.gz file from the server to my PC. 
    Why is it so slow?
    Filezilla connecting to SSH on custom port 2772.
    Are you rate-limiting non-default ports?
    
    DigitalOcean ssh speed on same setup, client and port was much much faster.
    Why is this so slow?

    12-07-2022, at least they do reply fast.

    Support answer.

    Dear client,
    
    Thank you for your request.
    
    We do not limit the bandwidth from our side. Your performance can vary according to the load on the host.
    
    The host server has a 10 Gbit/s uplink. The bandwidth is shared and we do not offer a guaranteed bandwidth.
    
    Experience shows that you can expect about 300 - 500 Mbit/s on average.
    
    Should you have any further questions please do not hesitate to contact us.

    I reply, trying to make sure they saw the actual speed.

    Did you see the screenshots attached?
    Between 600Kib/S and 1.6Mib/S
    Is that acceptable?
    
    Now it's 2.1 Mib/S
    Is the host server I'm on overloaded?

    Reply came fast again.

    Can you try download this files to your server?
    >>https://speed.hetzner.de/
    
    What speeds are you getting?
    Downloading to my PC from your link.
    Speed about 1.7 MB/s
    A bit better but still low.

    Tests show similar slightly higher speeds but still low.

    It’s probably the distance from them to me.

    As long as Cloudflare can get the files much faster it’s no big deal just annoying when copying backups out from their server.

    Went ahead and took a screenshot from the Hetzner Cloud Control Panel for our new Hezner server. Not even reached 3MBps during the transfer and you can see it’s fluctuating a lot?

    Hetzner Control Panel shows maximum network transfer bellow 3MBps
    Hetzner Control Panel shows maximum network transfer bellow 3MBps

    If you want to try DigitalOcean try it with this link bellow to get $100 FREE credit for 60 days.
    https://rex.red/do


    You get $100 free credit for 60 days and you can try different droplets or managed stuff.

    Hetzner offers you 20 EUR FREE credit with my referral link here https://rex.red/hetzner

    After you use your free 20 EUR free credit if you pay at least 10 EUR I get 10 EUR free credit.

    The Hetzner link I used to signup gave me 20 euro from 11 July 2022 but the credits expire on 01 September 2022.

    Hmm. that’s a bit on the short end.

    Looking forward to hear Cloudflare introduces it’s own hosting plans.

    Any comments?

    Please write bellow, I still believe Hetzner is great value for money after learning to live with their problems.

    Conclusion

    After using Hetzner for a while update on 16 July 2022.

    The Hetzner cpx11 cloud server is indeed faster than a $6 DigitalOcean droplet. Really happy about that.

    Realized, recently, Cloudflare has an Email service in Beta.

    Already using free email forwarders from CloudFlare.

    The only problem left is WordPress not sending email, that I plan to use with Google Could Gmail API.

    Not the paid Google Workspaces (that’s super easy to setup) but by using the Gmail API to send SMTP emails thru Google Could Oauth client id and client secret.

    If the Gmail SMTP works, there is no need for email on the Hetzner server anymore.

    This would make the migration to another Hetzner cloud server or another cloud server provider in the future much easier with a backup and restore script.

    By the way, for a while, since migrating away from Centos 7 (end of support drama with RedHat Centos 8 Stream), I can say that RockyLinux 8 (8.6) is the choice OS now for me.

    Really like to see RockyLinux 8.6 being one of the easy cloud server spin-up options on Hetzner and DigitalOcean.

    Update Hetzner vs Digital Ocean in 2023 and plans for 2024

    Since my move back to Digital Ocean not much changed other than actively using Couldflare R2 storage for web workloads.

    File storage in Cloudflare R2 is really easy and keeping up with the fees can be managed with billing alerts.

    In general, I love Cloudflare CDN because it can make a slow website blazingly fast. This website hopefully was super fast to load thankfully there was a cache Hit and not a cache Miss in your response headers for this page.

    I added a referral link to Hetzner to be fair. Anyone wanting to try one can try both like this

    Digital Ocean https://rex.red/do

    Hetzner https://rex.red/hetzner

    Digital Ocean works fine for me so far no complains with the faster storage droplets versions.

  • Best Linux distro 2021 RHEL vs Debian based

    Best Linux distro 2021 RHEL vs Debian based

    Best linux distro 2021 RHEL vs Debian based

    The best linux distribution of 2021 is not easy to decide. First choice is if you prefer a Linux distro that is RHEL based or Debian based.

    For a Linux server or a Linux desktop the requirements are quite different. There is no best linux distro really. Most of the established Linux distributions are great to use.

    Put the names of most known Linux distros. in a hat. Pick one, that’s the best distro for 2021 and 2022. Jokes aside, you should choose what you are even slightly used to.

    RHEL based Linux distributions

    If you goal is to use Linux in a professional environment – at work that is. RHEL based distros. will make you familiar to the Linux enterprise environment and things will be much more familiar on Red Hat Enterprise Linux (RHEL) once You used a similar OS.

    Linux distro for server

    For a server, you want to choose a distro that is well known and stable. Good reputation is very important. Tested packages before release is much more important. Long support and updated and running without crashing are basic requirements for a Linux server.

    Red Hat Enterprise Linux – RHEL

    The OS that many Linux distros. are based on is a top-tier enterprise Linux distro. With top support, security updates for critical operations. This one is not free but Red Hat have a developer subscription licensing program that allows for 16 production RHEL instances for free. More about RHEL Developer subscription here.

    Centos 8 / Centos Stream

    Centos 8 and Centos Stream have caused some controversy recently. Centos 7 was a downstream release distro. Updates were released on Centos 6 and 7 after they were released on RHEL 6 or 7. Now Centos 8 is upstream compared to RHEL 8. This means, updates are sent to Centos first then to RHEL. That places Centos after Fedora and before RHEL in the updates flow making Centos a testing step before RHEL instead of using fully tested packages.

    With all the problems Centos 8 and Centos Stream is still a great Linux server distro to consider. Centos is free.

    More about Centos 8 download page.

    Alma Linux & Rocky Linux

    Since the Centos 8 announcement, people have been looking for a new RHEL based distro that is downstream from RHEL. For this, these new distros. where recently created basically rebranding RHEL sources and adding their own to make a new distro.

    I’ve tried Rocky Linux and the setup was the same as Centos 8.

    Oracle Linux 8

    Oracle is a huge company known mostly for Oracle Database and Java but I won’t go into details there. The Oracle Linux 8 is binary compatible with RHEL 8 and Many things are the same as in the Red Hat distro but they mention their kernel is unbreakable as part of the name. They have paid support available for Oracle Linux 8 but the base version is free.

    Read more about Oracle Linux 8

    Debian 11

    Debian is one of the main well known GNU/Linux distribution. It is completely open source. It’s one of the oldest Linux operating systems.

    Debian is actively developed and maintained by a community of volunteers. It might be my next choice for our linux web server.

    Debian download page

    Ubuntu Server 21 LTS

    Ubuntu is based on the Debian distro. It is very popular for both desktop and server.

    The LTS in the release details stands fro Long Term Support and it’s what you would want to use in general. It’s one of the default choices when setting up a new Linux server on AWS or Microsoft Azure or Google Cloud.

    Download Ubuntu Server

    Linux for Desktop

    Linux has conquered the world of servers and even smartphones and tablets. Android is based on a modified version of Linux. For Desktop, Linux didn’t do so well. Crome-books might change that in the future.

    Fedora 34 Workstation

    A RHEL based linux distribution that Linus Torwalds (the maker of Linux and Linux kernel) claims to be using on his desktop computers or laptops.

    Gets the newest packages first but can be unstable.

    Download Fedora

    Ubuntu Desktop LTS

    Ubuntu is a more stable distro for those who prefer Debian based distros.

    Download Ubuntu Desktop

    Arch Linux

    Never tried it but Arch linux users are very happy (vocal) with it so it’s worth trying it.

    Download Arch Linux

    Manjaro

    Arch-based Linux distro that it’s user also like to talk about a lot.

    Download Manjaro Linux

    Distro for NAS

    For a network attached storage or NAS, the best Linux distro is Open Media Valut a debian based distro.

    Live / Portable

    These are specialized distros. that are mostly used as a Live Linux instance from a USB flash drive or a DVD/ISO file without persistence on disk.

    Kali Linux

    Kali Linux is a specialized distribution for pen-testing. It’s mostly used by security professionals or ethical hacker or white hat hackers.

    Get Kali Linux

    SliTaz

    SliTaz is a light-weight linux distribution ideal for a portable OS on a USB flash drive. It will work with older hardware and the size is very small.

    Download SliTaz

    Conclusion

    Try any of these or any other distros you might want to look at. For server would I choose Centos 8 and for Desktop Fedora but that’s my preference. You might like Arch more or Ubntu or even Oracle Linux.

    You can always try another distribution later.

  • Linux Check Disk Space Commands

    Linux Check Disk Space Commands

    How to check disk space in Linux command line. The command df shows you free disk space and du returns the disk usage statistics for various files and folders.

    df command

    The df command shows disk usage statistics and it stands for “Disk Free”.

    The df command bellow without any options will return the disk size, disk used, available size, disk free percentage and mount point for all system partitions.

    df 

    df Example

    [dragos@localhost ~]$ df
    Filesystem          1K-blocks    Used Available Use% Mounted on
    devtmpfs               900440       0    900440   0% /dev
    tmpfs                  929904     168    929736   1% /dev/shm
    tmpfs                  929904   82060    847844   9% /run
    tmpfs                  929904       0    929904   0% /sys/fs/cgroup
    /dev/mapper/cl-root  39687236 8365356  31321880  22% /
    /dev/sda2             1038336  370900    667436  36% /boot
    /dev/mapper/cl-home  19372032 2332336  17039696  13% /home
    /dev/sda1              613184    7404    605780   2% /boot/efi
    tmpfs                  185980    1184    184796   1% /run/user/42
    tmpfs                  185980      92    185888   1% /run/user/1004
    [dragos@localhost ~]$

    If you want to disk size is displayed in human readable format MB,GB,TB instead of bytes use the -h option.

    df -h

    df -h example

    [dragos@localhost ~]$ df -h
    Filesystem           Size  Used Avail Use% Mounted on
    devtmpfs             880M     0  880M   0% /dev
    tmpfs                909M  168K  908M   1% /dev/shm
    tmpfs                909M   81M  828M   9% /run
    tmpfs                909M     0  909M   0% /sys/fs/cgroup
    /dev/mapper/cl-root   38G  8.0G   30G  22% /
    /dev/sda2           1014M  363M  652M  36% /boot
    /dev/mapper/cl-home   19G  2.3G   17G  13% /home
    /dev/sda1            599M  7.3M  592M   2% /boot/efi
    tmpfs                182M  1.2M  181M   1% /run/user/42
    tmpfs                182M   92K  182M   1% /run/user/1004
    [dragos@localhost ~]$

    To see all partitons (pseudo, duplicate, inaccessible) use the -a option.

    df -ah

    df -a example

    [dragos@localhost ~]$ df -ah
    Filesystem           Size  Used Avail Use% Mounted on
    sysfs                   0     0     0    - /sys
    proc                    0     0     0    - /proc
    devtmpfs             880M     0  880M   0% /dev
    securityfs              0     0     0    - /sys/kernel/security
    tmpfs                909M  168K  908M   1% /dev/shm
    devpts                  0     0     0    - /dev/pts
    tmpfs                909M   81M  828M   9% /run
    tmpfs                909M     0  909M   0% /sys/fs/cgroup
    cgroup                  0     0     0    - /sys/fs/cgroup/systemd
    pstore                  0     0     0    - /sys/fs/pstore
    efivarfs                0     0     0    - /sys/firmware/efi/efivars
    ........
    tmpfs                182M   92K  182M   1% /run/user/1004
    gvfsd-fuse              0     0     0    - /run/user/1004/gvfs
    tmpfs                909M   81M  828M   9% /run/netns
    [dragos@localhost ~]$

    To also see the file system type use df -T option. Disk free human readable and showing file system type also.

    df -hT

    df -T example

    [dragos@localhost ~]$ df -hT
    Filesystem          Type      Size  Used Avail Use% Mounted on
    devtmpfs            devtmpfs  880M     0  880M   0% /dev
    tmpfs               tmpfs     909M  168K  908M   1% /dev/shm
    tmpfs               tmpfs     909M   81M  828M   9% /run
    tmpfs               tmpfs     909M     0  909M   0% /sys/fs/cgroup
    /dev/mapper/cl-root xfs        38G  8.0G   30G  22% /
    /dev/sda2           xfs      1014M  363M  652M  36% /boot
    /dev/mapper/cl-home xfs        19G  2.3G   17G  13% /home
    /dev/sda1           vfat      599M  7.3M  592M   2% /boot/efi
    tmpfs               tmpfs     182M  1.2M  181M   1% /run/user/42
    tmpfs               tmpfs     182M   92K  182M   1% /run/user/1004
    [dragos@localhost ~]$

    Most useful options for df.

      -a, --all             include pseudo, duplicate, inaccessible file systems
      -h, --human-readable  print sizes in powers of 1024 (e.g., 1023M)
      -T, --print-type      print file system type

    du command

    The du command shows disk usage of directories and files. It’s useful to find folders and files that use a lot of disk space.

    List all files and folders with their size in the current directory.

    du -h 

    Show disk usage of all files

    du -ah

    ls

    Lists folders and files and shows their size on disk, human readable.

    ls -al
    
    ls -alh

    stat

    Display the used disk space of a folder.

    [dragos@localhost ~]$ stat /home/dragos
      File: /home/dragos
      Size: 219             Blocks: 0          IO Block: 4096   directory
    Device: fd02h/64770d    Inode: 33807434    Links: 8
    Access: (0700/drwx------)  Uid: ( 1004/  dragos)   Gid: ( 1004/  dragos)
    Access: 2021-09-15 11:05:28.795212138 +0300
    Modify: 2021-09-15 10:12:34.093313726 +0300
    Change: 2021-09-15 10:12:34.093313726 +0300
     Birth: -
    [dragos@localhost ~]$
  • How to Remove Directory in Linux

    How to Remove Directory in Linux

    How to Remove or Delete Directory in Linux

    To delete a directory in Linux remove command to use is rm or rmdir. Both work fine but there is an important difference between how rm and rmdir remove a directory.

    Caution

    If you delete a directory from the GUI even in Linux, the folder is moved to the Trash bin. It is not really deleted right away.

    If you remove a file using command line it skips the Trash bin – the directory gets deleted now not later!

    Use ls /directory-path/your directory/ to be sure this is the actual directory you want the be deleted.

    rm command

    The rm command can be used to delete directories but also file and also everything if you are not careful.

    There are many jokes and memes about the command “rm -rf /” but you should know what it does. It deletes everything, no questions asked -f and recursive in sub-directories -r in the root of your system / so it really deletes everything.

    rm -r directory/

    -r is for recursive – subfolders and files

    rm -rf directory/

    rf is recursive and force – no questions – deletes all it can in the target directory you specify.

    Example

    [dragos@localhost ~]$ mkdir test-diy
    [dragos@localhost ~]$ ls | grep diy
    test-diy
    [dragos@localhost ~]$ rm test-diy/
    rm: cannot remove 'test-diy/': Is a directory
    [dragos@localhost ~]$ rm -r test-diy/
    [dragos@localhost ~]$ mkdir -p test-diy/test1/test2/test3
    [dragos@localhost ~]$ tree | grep test
    ├── printtest
    │   │   │   │   │   └── testfile1
    │   │   │   │   └── testfile2
    │   │   └── testfile3
    │   └── test4
    ├── test
    ├── test1
    ├── test3
    ├── test-diy
    │   └── test1
    │       └── test2
    │           └── test3
    └── test.html
    [dragos@localhost ~]$ rm -r test-diy/
    [dragos@localhost ~]$ tree | grep test
    ├── printtest
    │   │   │   │   │   └── testfile1
    │   │   │   │   └── testfile2
    │   │   └── testfile3
    │   └── test4
    ├── test
    ├── test1
    ├── test3
    └── test.html
    [dragos@localhost ~]$
    [dragos@localhost ~]$ rm -r rex.red/
    [dragos@localhost ~]$ tree
    .
    ├── 8
    │   └── nine
    ├── file
    ├── filed
    ├── fileee
    ├── logfiles
    ├── printtest
    ├── test
    ├── test1
    ├── test3
    └── test.html
    
    2 directories, 9 files
    [dragos@localhost ~]$
    [dragos@localhost ~]$ rm * -r
    [dragos@localhost ~]$ tree
    .
    
    0 directories, 0 files
    [dragos@localhost ~]$
    [dragos@localhost ~]$ mkdir -p test1/test2/test3/test4
    [dragos@localhost ~]$ tree
    .
    └── test1
        └── test2
            └── test3
                └── test4
    
    4 directories, 0 files
    [dragos@localhost ~]$

    rmdir command

    It deletes a directory without having to specify extra parameters.

    In a way it is easier and safer than rm with the -rf options.

    rmdir /directory-path-to/your-directory

    or

    cd /directory-path-to
    rmdir your-directory

    or just

    rmdir your-directory/

    If the directory is not empty you will receive the error

    [dragos@localhost ~]$ rmdir rex.red/
    rmdir: failed to remove 'rex.red/': Directory not empty

    To delete a non-empty directory use rm -r directory/ instead.

    Example

    [dragos@localhost ~]$ mkdir test-diy.rednumberone.com
    [dragos@localhost ~]$ ls
    8  file  filed  fileee  logfiles  printtest  rex.red  test  test1  test3  test-diy.rednumberone.com  test.html
    [dragos@localhost ~]$ ls | grep diy
    test-diy.rednumberone.com
    [dragos@localhost ~]$ rmdir test-diy.rednumberone.com
    [dragos@localhost ~]$ ls | grep diy
    [dragos@localhost ~]$ ls
    8  file  filed  fileee  logfiles  printtest  rex.red  test  test1  test3  test.html
    [dragos@localhost ~]$

    Remove directory with find

    Find is a command line utility that can list files or directories but with the exec command and {} + option it executes the new command and passes it’s output directory path as an argument.

    If you want to delete one or multiple directories it’s better to run the find command without exec to see if this is really what you want to remove in the first place.

    find /home/dragos/test1 -type d -name '*-testlogs'

    If you would like to find and delete all *-testlogs folders / directories you can use the bellow command.

    find /home/dragos/test1 -type d -name '*-testlogs' -exec rm -r {} +
  • How to Compress and Extract Files using the tar command on Linux

    How to Compress and Extract Files using the tar command on Linux

    How to Compress and Extract Files using the tar command on Linux and How to create tar.gz file in Linux command line

    Compress files

    The tar command is used to pack and compress files and directories on Linux.

    The archived files are usually named .tar.gz or .tgz and are called usually tarballs. As with many Linux commands, there are many options that can be used with the tar command.

    Tar can compress and also extract .tar.gz or .tgz archives.

    Example command to backup multiple directories into a tarball.

    tar -czf /var/dibackup/backup-$datetxt.tar.gz /etc/ /home/ /var/www/ /var/dibackup/db-backup/

    Here -czf means create a new archive, use gzip, specify the archive file name and compress the following files/directories – multiple paths are passed separated by space.

    If you want to see more details about the process you can also use the -v option, v is for verbose listing of processed files.

    tar -czvf /var/dibackup/backup-$datetxt.tar.gz /etc/ /home/ /var/www/ /var/dibackup/db-backup/

    If you would like to exclude some directories you can use the –exclude option

    tar -czvf /var/dibackup/backup-$datetxt.tar.gz /etc/ /home/ /var/www/ /var/dibackup/db-backup/ --exclude=/home/dragos/Downloads

    Once finished, you will have a .tar.gz or .tgz file that is the archive.

    Test – list archive contents

    To list all files in the archive. Lists all files in archive-file.tgz verbosely.

    tar -tvf archive-file.tgz

    Extracting files from archive

    When you need to extract the archive to the current directory you can use use the command bellow. Extracts all files from archive-file.tgz.

    tar -xf archive-file.tgz

    or to specify gzip

    tar -xzf archive-file.tgz

    or for verbose

    tar -xzvf archive-file.tgz

    Extract to directory

    If you want the archive to be extracted to a specific directory you can use the -C option (capital C) change to directory DIR.

    tar -xzf archive-file.tgz -C /home/dragos/archive-extracted

    Using bzip2 instead of gzip

    To use bzip2 compression instead of gzip, replace the -z option in the above commands with -j

    tar command options used

    Options used explanations:
    -c, --create               create a new archive
    -z, --gzip, --gunzip, --ungzip   filter the archive through gzip
    -f, --file=ARCHIVE         use archive file or device ARCHIVE
    -v, --verbose              verbosely list files processed
    -t, --list                 list the contents of an archive
    -j, --bzip2                filter the archive through bzip2
    --exclude=PATTERN      exclude files, given as a PATTERN
    -C, --directory=DIR        change to directory DIR
    

    All command options

    To see the available options you can see the man page or help or the tar command.

    tar --help
    man tar
    

    If you are using Windows 10 or Windows 11 there is a good archiving tool called 7-Zip. You can use it to create or extract archives. Even archives created with tar on Linux.

  • Linux how o set environment variable

    Linux how o set environment variable

    Linux how o set environment variable

    How to set environment variable in Linux.

    Set environment variables in Linux

    To set a new environment variable, use the export command.

    export NAME=VALUE

    For example to set the environment variable called TEST_HOME you can run this command.

    export TEST_HOME=/home/rex.red/test_service_home
    

    This prints the value of the variable you set earlier.

    echo $TEST_HOME

    Unsetting an environment variable

    The following command will be used to unset the environment variable.

    unset VARIABLENAME

    Set a persistent environment variable

    If you set the variable from the shell, once you log out of your session, the variable is lost. To make an environment variable persistent across sessions you can export the variable in the user’s profile script.

    vim ~/.bash_profile
    # User specific environment and startup programs
    export TEST_HOME=/home/rex.red/test_service_home

    Exit vim :wq Logout and reconnect

    [dragos@localhost ~]$ echo $TEST_HOME
    /home/rex.red/test_service_home
    [dragos@localhost ~]$

    Now the variable will be set when your session starts.

    View current environment variables

    To view the current environment variables use the -p option.

    [dragos@localhost ~]$ export -p
    [dragos@localhost ~]$ echo $TEST_HOME
    /home/test_service_home
    [dragos@localhost ~]$ export -p
    declare -x DISPLAY="localhost:10.0"
    declare -x GDK_BACKEND="x11"
    declare -x HISTCONTROL="ignoredups"
    declare -x HISTSIZE="1000"
    declare -x HOME="/home/dragos"
    declare -x HOSTNAME="localhost.localdomain"
    declare -x LANG="en_GB.UTF-8"
    declare -x LOGNAME="dragos"
    declare -x OLDPWD
    declare -x PATH="/home/dragos/.local/bin:/home/dragos/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin"
    declare -x PWD="/home/dragos"
    declare -x SHELL="/bin/bash"
    declare -x SHLVL="1"
    declare -x SSH_TTY="/dev/pts/0"
    declare -x TERM="xterm"
    declare -x TEST_HOME="/home/test_service_home"
    declare -x USER="dragos"
    declare -x XDG_DATA_DIRS="/home/dragos/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share"
    declare -x XDG_RUNTIME_DIR="/run/user/1004"
    declare -x XDG_SESSION_ID="77"
    [dragos@localhost ~]$

    This works on any Linux distribution, Redhat based, Debian based, etc…

  • How to create a file in Linux using Terminal

    How to create a file in Linux using Terminal

    How to create a file in Linux using Terminal or SSH

    How to create a file in Linux using Terminal, Command line interface or SSH.

    There are a few ways to create a new empty file or redirect the output of a command to a new file. To create an empty file, any of these commands can accomplish that without having to install any extra packages or modules.

    touch

    Touch creates an empty file in the path you specify. Easy

    touch file
    touch /var/rex.red/file1

    >file

    Simply created an empty file with the name you write.

    >file

    or in a directory

    >/var/rex.red/test4

    echo

    You can also add text with echo but this creates a new empty file.

    echo -n >file
    echo >/var/rex.red/file

    printf

    Same idea as with echo but using prinf if you prefer it like this.

    printf ''>file

    Create file from text output

    Create non-empty file

    If you need to save a file but with contents it’s still pretty easy.

    echo

    echo 'file contents' > file

    printf

    printf 'file contents\ntest\n' > file

    ls > file

    ls -lh /var/log/ > logfiles

    cat >

    cat file1 > file2

    vim

    Create the file and edit it. Insert key – When finished save it :wq to save and exit vim.

    vim file1 
  • Secret Lesser  known useful Linux commands

    Secret Lesser known useful Linux commands

    tree

    The tree command will list you directory, files and sub folders contents in an easy to see way. No need for repeated ls commands. This can be useful to get an overview of all subfolders of the target directory.

    tree /var/log/
    tree rex.red/
    rex.red/
    ├── folder-4
    ├── folder-5
    ├── folder-6
    │   ├── folder7
    │   │   ├── eeefolder_3333
    │   │   │   ├── nine
    │   │   │   │   └── testfile1
    │   │   │   └── testfile2
    │   │   ├── folder
    │   │   ├── folder_33
    │   │   │   └── nine
    │   │   ├── folder_3333
    │   │   │   └── nine
    │   │   └── folder_8
    │   │       └── nine
    │   └── testfile3
    ├── folder-one
    ├── folder-three
    └── folder-two
    
      -p            Print the protections for each file.
      -u            Displays file owner or UID number.
      -g            Displays file group owner or GID number.
      -s            Print the size in bytes of each file.
      -h            Print the size in a more human readable way.
    
    
    [dragos@localhost ~]$ tree -pughs rex.red/
    rex.red/
    ├── [drwxrwxr-x dragos   dragos       6]  folder-4
    ├── [drwxrwxr-x dragos   dragos       6]  folder-5
    ├── [drwxrwxr-x dragos   dragos      38]  folder-6
    │   ├── [drwxrwxr-x dragos   dragos      94]  folder7
    │   │   ├── [drwxrwxr-x dragos   dragos      35]  eeefolder_3333
    │   │   │   ├── [drwxrwxr-x dragos   dragos      23]  nine
    │   │   │   │   └── [-rw-rw-r-- dragos   dragos       0]  testfile1
    │   │   │   └── [-rw-rw-r-- dragos   dragos       0]  testfile2
    │   │   ├── [drwxrwxr-x dragos   dragos       6]  folder
    │   │   ├── [drwxrwxr-x dragos   dragos      18]  folder_33
    │   │   │   └── [drwxrwxr-x dragos   dragos       6]  nine
    │   │   ├── [drwxrwxr-x dragos   dragos      18]  folder_3333
    │   │   │   └── [drwxrwxr-x dragos   dragos       6]  nine
    │   │   └── [drwxrwxr-x dragos   dragos      18]  folder_8
    │   │       └── [drwxrwxr-x dragos   dragos       6]  nine
    │   └── [-rw-rw-r-- dragos   dragos       0]  testfile3
    ├── [drwxrwxr-x dragos   dragos       6]  folder-one
    ├── [drwxrwxr-x dragos   dragos       6]  folder-three
    └── [drwxrwxr-x dragos   dragos       6]  folder-two
    
    16 directories, 3 files
    [dragos@localhost ~]$
    

    pstree

    [dragos@localhost ~]$ pstree

    Tree but for precesses. Shows what processes originate from other processes.

    kill -15 SIGTERM

    Sends the SIGTERM signal to the process and allows it to exit gracefully. That process might hang so the next one is more drastic.

    sudo kill -15 PID
    [dragos@localhost ~]$ sudo kill -15 3778529
    [sudo] password for dragos:
    [dragos@localhost ~]$

    sudo kill -9 KILL

    Stop the process, end it now and don’t wait for anything.

    kill -9 PID

    [dragos@localhost ~]

    $ sudo kill -9 3778526
    

    ps -aux | grep log

    List processes piped into grep to find a hanging process. Extremely useful for finding what is happening with a process that is still running but takes much longer than expected. You can get some hints about what is wrong using this command combination.

    sudo !!

    yum update 
    sudo !!
    [dragos@localhost ~]$ yum update
    Error: This command has to be run with superuser privileges (under the root user on most systems).
    [dragos@localhost ~]$ sudo !!
    sudo yum update
    [sudo] password for dragos:
    Last metadata expiration check: 2:55:04 ago on Tue 31 Aug 2021 13:10:23 EEST.
    Dependencies resolved.
    Nothing to do.
    Complete!
    [dragos@localhost ~]$
    

    Get public ip

    curl ifconfig.io Public ip.

    [dragos@localhost ~]$ curl ifconfig.io
    111.222.333.444
    
  • Commands any Linux Sysadmin should learn first

    Commands any Linux Sysadmin should learn first

    Commands any Linux Sysadmin should learn first.

    These are the commands any Linux Sysadmin should learn first.

    These are some of the most useful commands for system administration and devops on Linux.

    They are command line tolls because most of the actions on system administration you would want to be automated and scheduled

    uptime

    Time passed since last restart and statistics about system load and users logged in since then.

    [dragos@localhost ~]$ uptime
     18:00:51 up 3 days, 20:59,  1 user,  load average: 0.01, 0.04, 0.00
    

    For a nicer look use the pretty option.

    uptime -p
    [dragos@localhost ~]$ uptime -p
    up 3 weeks, 3 days, 21 hours

    top

    Shows system statistics and resource allocation.

    CPU and RAM allocation overview list.

    top

    alias 

    alias command shortcut name = “the actual command”

    alias sayhello="echo ""Hello World!"""
    [dragos@localhost rex.red]$ alias sayhello="echo ""Hello World!"""
    [dragos@localhost rex.red]$ sayhello
    Hello World!
    [dragos@localhost rex.red]$
    This will last while you are still logged in. If you log out and logon again, the alias will be gone.

    Permanent alias

    Making the alias permanent for your user. You save it in your .bashrc file.

    vim ~/.bashrc

    Add the alias at the end of the file.

    # User specific aliases and functions
    #My Aliases
    alias sayhello="echo ""Hello World!"""

    Save the file – in vim Esc then :wq enter

    Make sure you use the file

    source ~/.bashrc

    Your alias is there even after a reboot.

    whereis

    Powerful command to locate files or directories on your drive.

    Most useful to find binaries of installed programs.

    whereis httpd

    free

    free -h

    RAM allocation and usage statistics.

    [dragos@localhost ~]$ free
                  total        used        free      shared  buff/cache   available
    Mem:        1859812      613712      453892       53532      792208     1036984
    Swap:       2158588      234220     1924368
    [dragos@localhost ~]$ free -h
                  total        used        free      shared  buff/cache   available
    Mem:          1.8Gi       599Mi       443Mi        52Mi       773Mi       1.0Gi
    Swap:         2.1Gi       228Mi       1.8Gi
    [dragos@localhost ~]$
    

    service

    service service-name action

    [dragos@localhost ~]$ service -h
    Usage: service < option > | --status-all | [ service_name [ command | --full-restart ] ]

    It’s useful to find problems with a daemon or service.

    It is also used to (start, stop, restart, try-restart, reload, force-reload, status) various services.

    service httpd status
    [dragos@localhost ~]$ service httpd status
    Redirecting to /bin/systemctl status httpd.service
    ● httpd.service - The Apache HTTP Server
       Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
      Drop-In: /usr/lib/systemd/system/httpd.service.d
               └─php-fpm.conf
       Active: inactive (dead)
         Docs: man:httpd.service(8)
    [dragos@localhost ~]$
    
    [dragos@localhost ~]$ sudo service httpd start
    [sudo] password for dragos:
    Redirecting to /bin/systemctl start httpd.service
    [dragos@localhost ~]$ sudo service httpd enable
    The service command supports only basic LSB actions (start, stop, restart, try-restart, reload, force-reload, status). For other actions, please try to use systemctl.
    [dragos@localhost ~]$
    

    You can start a service but to enable it on startup use systemctl.

    systemctl

    sudo systemctl restart httpd
    sudo systemctl reload httpd
    sudo systemctl stop httpd
    sudo systemctl start httpd
    sudo systemctl enable httpd
    sudo systemctl status httpd
    [dragos@localhost ~]$ sudo service httpd start
    [sudo] password for dragos:
    Redirecting to /bin/systemctl start httpd.service
    [dragos@localhost ~]$ sudo service httpd enable
    The service command supports only basic LSB actions (start, stop, restart, try-restart, reload, force-reload, status). For other actions, please try to use systemctl.
    [dragos@localhost ~]$ sudo systemctl restart httpd
    [dragos@localhost ~]$ sudo systemctl reload httpd
    [dragos@localhost ~]$ sudo systemctl stop httpd
    [dragos@localhost ~]$ sudo systemctl start httpd
    [dragos@localhost ~]$ sudo systemctl enable httpd
    Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service.
    [dragos@localhost ~]$ sudo systemctl status httpd
    ● httpd.service - The Apache HTTP Server
       Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
      Drop-In: /usr/lib/systemd/system/httpd.service.d
               └─php-fpm.conf
       Active: active (running) since Tue 2021-08-31 18:36:43 EEST; 11s ago
         Docs: man:httpd.service(8)
     Main PID: 3778525 (httpd)
       Status: "Running, listening on: port 80"
        Tasks: 213 (limit: 11255)
       Memory: 26.1M
       CGroup: /system.slice/httpd.service
               ├─3778525 /usr/sbin/httpd -DFOREGROUND
               ├─3778526 /usr/sbin/httpd -DFOREGROUND
               ├─3778527 /usr/sbin/httpd -DFOREGROUND
               ├─3778528 /usr/sbin/httpd -DFOREGROUND
               └─3778529 /usr/sbin/httpd -DFOREGROUND
    
    Aug 31 18:36:43 localhost.localdomain systemd[1]: Starting The Apache HTTP Server...
    Aug 31 18:36:43 localhost.localdomain systemd[1]: Started The Apache HTTP Server.
    Aug 31 18:36:43 localhost.localdomain httpd[3778525]: Server configured, listening on: port 80
    lines 1-21/21 (END)
    

    dig

    Complete DNS query to find any record related to a domain, name server, root nameserver

    dig rex.red
    [dragos@localhost ~]$ dig rex.red
    
    ; <<>> DiG 9.11.26-RedHat-9.11.26-4.el8_4 <<>> rex.red
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 29461
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
    
    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4000
    ;; QUESTION SECTION:
    ;rex.red.                       IN      A
    
    ;; ANSWER SECTION:
    rex.red.                299     IN      A       172.67.218.197
    rex.red.                299     IN      A       104.21.38.42
    
    ;; Query time: 347 msec
    ;; SERVER: 10.4.60.20#53(10.4.60.20)
    ;; WHEN: Tue Aug 31 10:51:06 EEST 2021
    ;; MSG SIZE  rcvd: 68
    

    The any parameter will give you all the DNS records of that domain. 

    It’s useful to get an overview of the setup of a domain.

    [dragos@localhost ~]$ dig rex.red any
    
    ; <<>> DiG 9.11.26-RedHat-9.11.26-4.el8_4 <<>> rex.red any
    ;; global options: +cmd
    ;; Got answer:
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 28600
    ;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 13
    
    ;; OPT PSEUDOSECTION:
    ; EDNS: version: 0, flags:; udp: 4000
    ;; QUESTION SECTION:
    ;rex.red.                       IN      ANY
    
    ;; ANSWER SECTION:
    rex.red.                243     IN      A       104.21.38.42
    rex.red.                243     IN      A       172.67.218.197
    rex.red.                3597    IN      NS      chan.ns.cloudflare.com.
    rex.red.                3597    IN      NS      alec.ns.cloudflare.com.
    rex.red.                3786    IN      HINFO   "RFC8482" ""
    
    ;; ADDITIONAL SECTION:
    chan.ns.cloudflare.com. 11396   IN      A       172.64.32.82
    chan.ns.cloudflare.com. 11396   IN      A       173.245.58.82
    chan.ns.cloudflare.com. 11396   IN      A       108.162.192.82
    chan.ns.cloudflare.com. 1707    IN      AAAA    2803:f800:50::6ca2:c052
    chan.ns.cloudflare.com. 1707    IN      AAAA    2a06:98c1:50::ac40:2052
    chan.ns.cloudflare.com. 1707    IN      AAAA    2606:4700:50::adf5:3a52
    alec.ns.cloudflare.com. 7750    IN      A       172.64.33.59
    alec.ns.cloudflare.com. 7750    IN      A       173.245.59.59
    alec.ns.cloudflare.com. 7750    IN      A       108.162.193.59
    alec.ns.cloudflare.com. 80123   IN      AAAA    2a06:98c1:50::ac40:213b
    alec.ns.cloudflare.com. 80123   IN      AAAA    2606:4700:58::adf5:3b3b
    alec.ns.cloudflare.com. 80123   IN      AAAA    2803:f800:50::6ca2:c13b
    
    ;; Query time: 3322 msec
    ;; SERVER: 10.4.60.20#53(10.4.60.20)
    ;; WHEN: Tue Aug 31 10:52:02 EEST 2021
    ;; MSG SIZE  rcvd: 408
    
    [dragos@localhost ~]$
    

    +nocomments option makes the response more compact by removing the comments of each section and giving you only the actual response.

    [dragos@localhost ~]$ dig rex.red any +nocomments
    
    ; <<>> DiG 9.11.26-RedHat-9.11.26-4.el8_4 <<>> rex.red any +nocomments
    ;; global options: +cmd
    ;rex.red.                       IN      ANY
    rex.red.                10      IN      A       172.67.218.197
    rex.red.                10      IN      A       104.21.38.42
    rex.red.                3364    IN      NS      chan.ns.cloudflare.com.
    rex.red.                3364    IN      NS      alec.ns.cloudflare.com.
    rex.red.                3553    IN      HINFO   "RFC8482" ""
    rex.red.                157     IN      TXT     "google-site-verification=C0S4gecD15hMlSjLUF0bGRNURsYoleGS-v_1zCJ6mr4"
    chan.ns.cloudflare.com. 11163   IN      A       173.245.58.82
    chan.ns.cloudflare.com. 11163   IN      A       108.162.192.82
    chan.ns.cloudflare.com. 11163   IN      A       172.64.32.82
    chan.ns.cloudflare.com. 1474    IN      AAAA    2a06:98c1:50::ac40:2052
    chan.ns.cloudflare.com. 1474    IN      AAAA    2606:4700:50::adf5:3a52
    chan.ns.cloudflare.com. 1474    IN      AAAA    2803:f800:50::6ca2:c052
    alec.ns.cloudflare.com. 7517    IN      A       173.245.59.59
    alec.ns.cloudflare.com. 7517    IN      A       108.162.193.59
    alec.ns.cloudflare.com. 7517    IN      A       172.64.33.59
    alec.ns.cloudflare.com. 79890   IN      AAAA    2606:4700:58::adf5:3b3b
    alec.ns.cloudflare.com. 79890   IN      AAAA    2803:f800:50::6ca2:c13b
    alec.ns.cloudflare.com. 79890   IN      AAAA    2a06:98c1:50::ac40:213b
    ;; Query time: 26 msec
    ;; SERVER: 10.4.60.20#53(10.4.60.20)
    ;; WHEN: Tue Aug 31 10:55:55 EEST 2021
    ;; MSG SIZE  rcvd: 489
    
    [dragos@localhost ~]$

    Looking ony at the TXT DNS records of the domain.

    [dragos@localhost ~]$ dig rex.red txt +nocomments
    
    ; <<>> DiG 9.11.26-RedHat-9.11.26-4.el8_4 <<>> rex.red txt +nocomments
    ;; global options: +cmd
    ;rex.red.                       IN      TXT
    rex.red.                26      IN      TXT     "google-site-verification=C0S4gecD15hMlSjLUF0bGRNURsYoleGS-v_1zCJ6mr4"
    ;; Query time: 0 msec
    ;; SERVER: 10.4.60.20#53(10.4.60.20)
    ;; WHEN: Tue Aug 31 10:58:06 EEST 2021
    ;; MSG SIZE  rcvd: 117
    
    [dragos@localhost ~]$
    

    The default is a which returns the IPv4 of the domain. 

    q-type   is one of (a,any,mx,ns,soa,hinfo,axfr,txt,…) [default:a]

    ifconfig

    List all interfaces

    ifconfig -a

    Enable the network card interface

    ifconfig eth0 down

    Disable the network card

    ifconfig eth0 up

    Configure the network interface

    ifconfig eth0 192.168.1.12
    ifconfig eth0 netmask 255.255.255.
    ifconfig eth0 broadcast 192.168.1.255

    netstat

    Shows active network connections 

    netstat

    Show all sockets 

    netstat -a

    Show statistics for all interfaces

    netstat -s

    Display interfaces

    netstat -i
    [dragos@localhost rex.red]$ netstat -h
    usage: netstat [-vWeenNcCF] [<Af>] -r         netstat {-V|--version|-h|--help}
           netstat [-vWnNcaeol] [<Socket> ...]
           netstat { [-vWeenNac] -I[<Iface>] | [-veenNac] -i | [-cnNe] -M | -s [-6tuw] } [delay]
    
            -r, --route              display routing table
            -I, --interfaces=<Iface> display interface table for <Iface>
            -i, --interfaces         display interface table
            -g, --groups             display multicast group memberships
            -s, --statistics         display networking statistics (like SNMP)
            -M, --masquerade         display masqueraded connections
    
            -v, --verbose            be verbose
            -W, --wide               don't truncate IP addresses
            -n, --numeric            don't resolve names
            --numeric-hosts          don't resolve host names
            --numeric-ports          don't resolve port names
            --numeric-users          don't resolve user names
            -N, --symbolic           resolve hardware names
            -e, --extend             display other/more information
            -p, --programs           display PID/Program name for sockets
            -o, --timers             display timers
            -c, --continuous         continuous listing
    
            -l, --listening          display listening server sockets
            -a, --all                display all sockets (default: connected)
            -F, --fib                display Forwarding Information Base (default)
            -C, --cache              display routing cache instead of FIB
            -Z, --context            display SELinux security context for sockets
    
    

    vim

    Command line text editors. Especially useful for editing configuration files in emergency situations.

    vi file
    vim  file
    nano file
  • How to zip and unzip files and folders in Linux

    How to zip and unzip files and folders in Linux

    How to zip and unzip files and folders in Linux

    Install Zip Unzip

    Install on RHEL, Centos, Fedora, Rocky Linux, etc.

    sudo yum install zip unzip

    Install on Debian, Ubuntu, etc.

    sudo apt-get install zip unzip

    Using zip and unzip to compress and extract files and folders.

    Current directory contents, files and one sub folder.

    ls -lh /home/dragos 
    total 8.0K
    drwxrwxr-x 2 dragos dragos 23  testdir
    -rw-rw-r-- 1 dragos dragos 37  testfile
    -rw-rw-r-- 1 dragos dragos 71  testfile2
    [dragos@localhost ~]$ ls -lh /home/dragos/testdir/
    total 4.0K
    -rw-rw-r-- 1 dragos dragos 35  innerfile
    

    Zip files and directories recursively

    This creates the zip file, the .zip extension is optional you can name it anything you like but .zip makes it more clear what it is later. 

    The * wildcard character tells zip everything in that directory. 

    [dragos@localhost ~]$ zip -r diyrednumberone.zip /home/dragos/*
      adding: home/dragos/testdir/ (stored 0%)
      adding: home/dragos/testdir/innerfile (deflated 80%)
      adding: home/dragos/testfile (deflated 57%)
      adding: home/dragos/testfile2 (deflated 68%)
    [dragos@localhost ~]$
    

    Zip files only

    Zip files only in first level directory – the one you specify or the current directory.

    zip archive-name.zip /path-to-files/

    Zipping test files

    [dragos@localhost ~]$ ls -lh /home/dragos
    total 12K
    -rw-rw-r-- 1 dragos dragos 760  diyrednumberone.zip
    drwxrwxr-x 2 dragos dragos  23  testdir
    -rw-rw-r-- 1 dragos dragos  37  testfile
    -rw-rw-r-- 1 dragos dragos  71  testfile2
    
    Moving the previous zip file to avoid confusion
    
    [dragos@localhost ~]$ mv diyrednumberone.zip testdir/
    
    
    Files are ready for zip
    
    [dragos@localhost ~]$ ls -lh /home/dragos
    total 8.0K
    drwxrwxr-x 2 dragos dragos 50  testdir
    -rw-rw-r-- 1 dragos dragos 37  testfile
    -rw-rw-r-- 1 dragos dragos 71  testfile2
    
    
    Compress the files and add them to a new zip file.
    
    [dragos@localhost ~]$ zip diyrednumberone_files.zip /home/dragos/*
      adding: home/dragos/testdir/ (stored 0%)
      adding: home/dragos/testfile (deflated 57%)
      adding: home/dragos/testfile2 (deflated 68%)
    [dragos@localhost ~]$
    
    
    Zip file is created
    
    [dragos@localhost ~]$ ls -lh /home/dragos 
    total 12K
    -rw-rw-r-- 1 dragos dragos 567  diyrednumberone_files.zip
    drwxrwxr-x 2 dragos dragos  50  testdir
    -rw-rw-r-- 1 dragos dragos  37  testfile
    -rw-rw-r-- 1 dragos dragos  71  testfile2
    

    Encrypted zip

    You can encrypt the zip file so that nobody can read the file contents without a password.

    zip -e diyrednumberone_files_enc.zip /home/dragos/*

    The -e parameter specifies the zip is to be encrypted and you will have to enter the password twice after pressing enter.

    [dragos@localhost ~]$ zip -e diyrednumberone_files_enc.zip /home/dragos/*
    Enter password:
    Verify password:
      adding: home/dragos/diyrednumberone_files.zip (stored 0%)
      adding: home/dragos/testdir/ (stored 0%)
      adding: home/dragos/testfile (deflated 57%)
      adding: home/dragos/testfile2 (deflated 68%)
    
    
    Zip command options
    
    [dragos@localhost ~]$ zip -h
    Copyright (c) 1990-2008 Info-ZIP - Type 'zip "-L"' for software license.
    Zip 3.0 (July 5th 2008). Usage:
    zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]
      The default action is to add or replace zipfile entries from list, which
      can include the special name - to compress standard input.
      If zipfile and list are omitted, zip compresses stdin to stdout.
      -f   freshen: only changed files  -u   update: only changed or new files
      -d   delete entries in zipfile    -m   move into zipfile (delete OS files)
      -r   recurse into directories     -j   junk (don't record) directory names
      -0   store only                   -l   convert LF to CR LF (-ll CR LF to LF)
      -1   compress faster              -9   compress better
      -q   quiet operation              -v   verbose operation/print version info
      -c   add one-line comments        -z   add zipfile comment
      -@   read names from stdin        -o   make zipfile as old as latest entry
      -x   exclude the following names  -i   include only the following names
      -F   fix zipfile (-FF try harder) -D   do not add directory entries
      -A   adjust self-extracting exe   -J   junk zipfile prefix (unzipsfx)
      -T   test zipfile integrity       -X   eXclude eXtra file attributes
      -y   store symbolic links as the link instead of the referenced file
      -e   encrypt                      -n   don't compress these suffixes
      -h2  show more help
    
    

    Unzip

    Extract zip to current directory

    unzip zipfile.zip 

    Extract to a specific directory -d sets the destination directory where the files will be extracted.

    unzip zipfile.zip -d /directory whereto extract/

    #
    [dragos@localhost ~]$ mkdir extracted/diyrednumberone
    [dragos@localhost ~]$ mkdir extracted/diyrednumberone_files
    [dragos@localhost ~]$ mkdir extracted/diyrednumberone_files_enc
    [dragos@localhost ~]$ ls extracted/
    diyrednumberone  diyrednumberone_files  diyrednumberone_files_enc
    [dragos@localhost ~]$ unzip testdir/diyrednumberone.zip -d extracted/diyrednumberone
    Archive:  testdir/diyrednumberone.zip
       creating: extracted/diyrednumberone/home/dragos/testdir/
      inflating: extracted/diyrednumberone/home/dragos/testdir/innerfile
      inflating: extracted/diyrednumberone/home/dragos/testfile
      inflating: extracted/diyrednumberone/home/dragos/testfile2
    [dragos@localhost ~]$ unzip diyrednumberone_files.zip -d extracted/diyrednumberone_files
    Archive:  diyrednumberone_files.zip
       creating: extracted/diyrednumberone_files/home/dragos/testdir/
      inflating: extracted/diyrednumberone_files/home/dragos/testfile
      inflating: extracted/diyrednumberone_files/home/dragos/testfile2
    [dragos@localhost ~]$ unzip diyrednumberone_files_enc.zip -d extracted/diyrednumberone_files_enc/
    Archive:  diyrednumberone_files_enc.zip
    [diyrednumberone_files_enc.zip] home/dragos/diyrednumberone_files.zip password:
     extracting: extracted/diyrednumberone_files_enc/home/dragos/diyrednumberone_files.zip
       creating: extracted/diyrednumberone_files_enc/home/dragos/testdir/
      inflating: extracted/diyrednumberone_files_enc/home/dragos/testfile
      inflating: extracted/diyrednumberone_files_enc/home/dragos/testfile2
    
    [dragos@localhost ~]$ ls -h extracted/diyrednumberone
    home
    [dragos@localhost ~]$ ls extracted/diyrednumberone/home/dragos/
    testdir  testfile  testfile2
    [dragos@localhost ~]$ ls extracted/diyrednumberone_files/home/dragos/
    testdir  testfile  testfile2
    [dragos@localhost ~]$ ls extracted/diyrednumberone/home/dragos/testdir/
    innerfile
    [dragos@localhost ~]$ ls extracted/diyrednumberone_files/home/dragos/testdir/
    [dragos@localhost ~]$ ls extracted/diyrednumberone_files_enc/home/dragos/
    diyrednumberone_files.zip  testdir  testfile  testfile2
    [dragos@localhost ~]$
    
    
    Unzip command options
    
    [dragos@localhost ~]$ unzip -h
    UnZip 6.00 of 20 April 2009, by Info-ZIP.  Maintained by C. Spieler.  Send
    bug reports using http://www.info-zip.org/zip-bug.html; see README for details.
    
    Usage: unzip [-Z] [-opts[modifiers]] file[.zip] [list] [-x xlist] [-d exdir]
      Default action is to extract files in list, except those in xlist, to exdir;
      file[.zip] may be a wildcard.  -Z => ZipInfo mode ("unzip -Z" for usage).
    
      -p  extract files to pipe, no messages     -l  list files (short format)
      -f  freshen existing files, create none    -t  test compressed archive data
      -u  update files, create if necessary      -z  display archive comment only
      -v  list verbosely/show version info       -T  timestamp archive to latest
      -x  exclude files that follow (in xlist)   -d  extract files into exdir
    modifiers:
      -n  never overwrite existing files         -q  quiet mode (-qq => quieter)
      -o  overwrite files WITHOUT prompting      -a  auto-convert any text files
      -j  junk paths (do not make directories)   -aa treat ALL files as text
      -U  use escapes for all non-ASCII Unicode  -UU ignore any Unicode fields
      -C  match filenames case-insensitively     -L  make (some) names lowercase
      -X  restore UID/GID info                   -V  retain VMS version numbers
      -K  keep setuid/setgid/tacky permissions   -M  pipe through "more" pager
      -O CHARSET  specify a character encoding for DOS, Windows and OS/2 archives
      -I CHARSET  specify a character encoding for UNIX and other archives
    
    See "unzip -hh" or unzip.txt for more help.  Examples:
      unzip data1 -x joe   => extract all files except joe from zipfile data1.zip
      unzip -p foo | more  => send contents of foo.zip via pipe into program more
      unzip -fo foo ReadMe => quietly replace existing ReadMe if archive file newer
    [dragos@localhost ~]$