Tag: Linux commands

  • 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.

  • 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 ~]$
    

  • Linux commands cheat sheet the most used list

    Linux commands cheat sheet the most used list

    Most useful Linux commands for daily 

    # Display how long has the system been running – since tle last restart.

    uptime

    # List directory contents

    ls
    ls /var/log/

    # List files in directory but better attributes and human-readable

    ls -ls 

    # List files in directory sorted by file date/time.

    ls -tlh 

    # Change directory 

    cd /var/log/ #will change current directory to /var/log/
    cd ~ # the ~ character indicates the current logged in user's home directory. 

    # Wildcards

    When filtering for files or directories you can use * to match multiple files.

    For example:

    ls -lht /var/log/*log

    This will list all files that have any name in the /var/log/ directory and their file names end with .log

    #Show file contents, can concatenate multiple files contents.

    cat /var/log/somefile.log
    cat /var/log/*.log

    # Sudo allows you to use super user commands under your username.

    To be able to issue sudo commands a user must me a member of the wheel group – rhel related distributions.

    sudo ls /var/log/

    # See any changes made to a log file, display anything that is being appended.

    tail -f /var/log/somefile
    tail -30f /var/log/somefile

    # Another way to monitor file changes is Less where you can press Ctrl+D to scroll up if you want to see more of previous changes. You quit less by pressing q on your keyboard.

    less /var/log/somefile

    # What is the name of the machine.

    hostname

    # For fqdn or long name

    hostname -f 

    # Help with a specific command

    Any command can accept the –help parameter option to display help with that command’s options that are available.

    ls --help
    cd --help
    tail --help 

    # Find matches of a string in another string or file.

    Here we cound for each file how many times the search text is found.

    grep -1c "Power Button: Found keys" -f /var/log/*

    # Using the pipe character | to combine commands in CLI (command line interface).

    Here grep will help us filter the file contents and see only what we need. The command output from cat is sent to grep that displays the data.

    sudo cat /var/log/secure | grep "COMMAND=/usr/bin/tail"