Jump to content

Linux commands

From LemonWiki共筆
(Redirected from Alternative Linux commands)

(1) Different Linux commands that achieve the same outcome, (2) Commands that are either equivalent or alike across Windows and Linux systems.


Help for command[edit]

Help for command:

Text file manipulation[edit]

Display the content of text file[edit]

Display the first lines of text file[edit]

  • head [options] filename (OS: Linux )
  • vi [options] filename (and press gg) (Linux )
  • vim [options] filename (and press gg) (Linux ); Open file and press gg for gVim (Win )

Display the first xxx bytes of text file[edit]

head -c 100 file_name

Display the last few lines of text file[edit]

Display the entire content of text file[edit]

  • vi [options] filename (Linux )
  • cat <filename> (Linux )
  • type <filename> (Win )

Display the partial content of large text file page by page[edit]

Display only certain lines by number[edit]

text processing - With the Linux "cat" command, how do I show only certain lines by number - Unix & Linux Stack Exchange

Show certain lines by line number[edit]

Show certain lines by line number

Newline count (count the number of lines of a file), word count[edit]

Icon_exclaim.gif linux - wc -l is NOT counting last of the file if it does not have end of line character - Stack Overflow

Save the console message as text file[edit]

Save the Unix manpage as plain text file

Search text in a file[edit]

  • grep command for multiple files: grep -ir "string to search" /path/to/directory or grep keyword /path/to/file (Linux )
  • vim: (1)vim [options] filename (2)press /keyword (Linux )
  • cat & grep: cat /path/to/file | grep keyword (Linux ) keyword is case sensitive

Search text in a compressed text file

Search text in files<ref>鳥哥的 Linux 私房菜 -- 學習 bash shell </ref>

Merge multiple plain text files[edit]

Merge multiple text files into one file

File operation[edit]

Find a file by filename[edit]

  • dir command (Win ) ex: dir /s filename <ref>How to find a file in MS-DOS.</ref><ref>/S 顯示指定目錄及所有子目錄中的檔案。 (引用自 dir /? 命令說明)</ref> Icon_exclaim.gif I have no idea to specify the file path to find the file.

Copy & overwrite file[edit]

Copy and overwrite file without prompt (confirmation)

Copy old directory to new directory[edit]

  • cp -a old_dir new_dir/ or cp -a old_dir/ new_dir/ (Linux )<ref>
from manual:
-a, --archive
              same as -dR --preserve=all
-d     same as --no-dereference --preserve=links
--preserve[=ATTR_LIST]
              preserve the specified attributes (default: mode,ownership,timestamps), if  possible  addi-
              tional attributes: context, links, xattr, all
-R, -r, --recursive
              copy directories recursively

</ref><ref>unix - How to copy with cp to include hidden files and hidden directories and their contents? - Super User</ref>

    • If the folder new_dir exists already, system will create the folder old_dir and all files and sub folders under old_dir will copy to the path new_dir/old_dir.
    • If the folder new_dir NOT exists, all files and sub folders under old_dir will copy to the folder new_dir.
  • cp -a old_dir/* new_dir/ (Linux ): All files and sub folders under old_dir will copy to the folder new_dir.
  • copy /Y old_dir new_dir/ (Win )<ref> /Y 不顯示覆寫現存目的檔案的確認提示。 (引用自 copy /? 命令說明)</ref>
  • make new directory & copy all old files to new directory
    • mkdir new_dir
    • cp old_dir/* new_dir
  • How to move all files in current folder to subfolder? - Ask Ubuntu

Rename (move) files or directory[edit]

Delete files or directory[edit]

delete all files or directory

  • rm -rf /Name_of_directory to delete all files under the 'Name_of_directory (Linux )<ref>[OPTION]
  • -r remove directories and their contents recursively;
  • -f ignore nonexistent files, never prompt

(above content cited from linux documentation: rm --help) </ref>

  • del Name_of_directory (Win )
    • After executed del Name_of_directory but the empty directory directory_name will be left.
    • Command delete is not available in Win XP
  • rsync
  • Using SFTP/FTP to connection to the server and delete selected files. Icon_exclaim.gif It may costs too much time if there are many files or sub folders!

Delete the files which their file name were matched with the naming rule when the number of files is too many.

Download file from remote server[edit]

  • FTP
  • wget (with progress bar): wget http://path.to/file
  • SVN update: svn up http://remote.svn.server/path/ /local/path/ --username=your_account and key in your SVN password <ref>using the www account su - www -c "svn up http://remote.svn.server/path/ /local/path/ --username=your_account --password=xxx" </ref>
  • more on File transfer methods


File compression and decompression[edit]

compress

decompress

ref

List directory or files / list directory contents[edit]

List only filenames and one file per line


Verify if a file or a directory exists

SET a=C:\path\to\file
REM -- If the directory was separated the \ symbol & the path NOT contains space
IF EXIST %a% (ECHO YES) ELSE (ECHO No)

SET a="C:\path\to\directory contains space\space"
REM -- If the directory was separated the \ symbol & the path contains space
IF EXIST %a% (ECHO YES) ELSE (ECHO No)

SET a=C:/path/to/file
REM -- If the directory was separated the / symbol, the next command replace / with \ symbol.
SET a=%a:/=\%
IF EXIST %a% (ECHO YES) ELSE (ECHO No)

troubleshooting

SET a = C:\path\to\file
REM -- Correct command: SET a=C:\path\to\file
IF EXIST %a% (ECHO YES) ELSE (ECHO No)
REM -- the returned result will not correct!

Print the current directory / where am i[edit]

Change directory to my home directory[edit]

How to list the ten most recent files in the same directory[edit]

How to list the ten most recent files in the same directory

network[edit]

show ip

ping Icon_exclaim.gif You may got no response if the server was disabled the ICMP (Internet Control Message Protocol) response.

  • ping domain_or_ip (Linux )
  • ping domain_or_ip -t (Win )

whois: search the information of domain (related: Domain Name Register)

TRACERT (trace route)

  • traceroute domain_or_ip (Linux ) & macOS icon_os_mac.png
  • tracert domain_or_ip -t (Win )

apache operation[edit]

check apache servie is running or not

Where is apache installed?<ref>Enabling and disabling services during start up in GNU/Linux | All about Linux</ref>

  • cat /etc/rc.d/rc.local if the apache service is already launched

check which mpm (multi processing module) apache is running

mysql operation[edit]

MySQL commands: 1. Exporting data into MySql sql file & 2. Importing data from MySql sql file

install package[edit]


System operation[edit]

How to find the location of an executable[edit]

Find the location of an executable e.g. Using where command on unix-like OS

show current time[edit]

More on the page Show current time

specify the location where Linux or MS-DOS looks when using a command[edit]

reboot the system/server[edit]

Shutdown system at a specific date time.

OS version[edit]

Show the process list[edit]

Show the process list & kill the high-resource-consumption process<ref>How do I Find Out Linux CPU Utilization? - nixCraft</ref><ref>Show All Running Processes in Linux</ref>

  1. Display the process list for Linux & macOS icon_os_mac.png
  2. keyin q to leave the process list

Kill the process[edit]

Find which process to be killed. And then keyin the process ID (PID):

Kill the process by process name<ref>Find and kill a process in one line using bash and regex - Stack Overflow</ref>

  • sudo kill $(ps aux | grep '<NAME>' | awk '{print $2}')

Kill the process by port number<ref>How to kill a process running on particular port in Linux? - Stack Overflow, lsof(8) - Linux man page</ref>

  • kill -9 $(lsof -ti:3000) 2>/dev/null: Force kill the process using port 3000. The 2>/dev/null suppresses error messages if no process is found. Replace 3000 with your target port number.
  • Alternative (shorter command): fuser -k 3000/tcp: Kill the process using TCP port 3000 (if fuser is available on your system)

Explanation:

  • lsof -ti:3000: Find the process ID (PID) using port 3000
    • -t: Output only the PID
    • -i:3000: Filter by port 3000
  • 2>/dev/null: Redirects error messages (stderr) to /dev/null (discards them) Useful when no process is found on the port to avoid error output
  • $(lsof -ti:3000): Command substitution<ref>Command Substitution (Bash Reference Manual)</ref>: executes the command inside $() and replaces it with the output
    • First runs lsof -ti:3000 to get the PID(s)
    • Then substitutes the PID(s) into the kill -9 command
    • Example: if port 3000 is used by PID 12345, kill -9 $(lsof -ti:3000) becomes kill -9 12345

Find process running on port[edit]

Find process running on port

Search and extract string from command output[edit]

System load average[edit]

Using WQL query to obtain Load capacity of each processor[edit]

on Win :

  • namespace: ROOT\CIMV2
  • WQL query: SELECT LoadPercentage FROM Win32_Processor; No need to divide by CPU cores number for Win8
  • output example: 24 (UInt16, 16 bit Unsigned Integer) unit: %
  • CPU usage = LoadPercentage; unit: %

Using PHP function to obtain system load average[edit]

on freebsd, Linux & macOS icon_os_mac.png :

System CPU usage[edit]

Using mpstat command to obtain CPU usage[edit]

Example result of mpstat 2 2 | grep -E '^Average' on Linux

Average:     all    1.31    0.00    0.25    0.00    0.00    0.00    0.00    0.00    0.00   98.43

The output of the mpstat command includes an "Average" line, which provides detailed information about CPU usage, similar to the %Cpu(s) line in the top command but with a slightly different format. Here's an explanation of the columns in the "Average" line:

  • all: This represents the average values for all CPU cores.

The subsequent columns represent percentages of CPU usage:

  • The first column (1.31) is the CPU usage by user-space processes, indicating the percentage of time the CPU is occupied by user programs and processes.
  • The second column (0.00) is the CPU usage by system kernel processes, indicating the percentage of time the CPU is occupied by the operating system kernel.
  • The third column (0.25) is the CPU usage by processes with a "nice" priority, representing the percentage of CPU time used by processes adjusted with the nice command.
  • The fourth column (0.00) is the CPU's idle time, indicating the percentage of time the CPU is not executing any tasks.
  • The fifth column (0.00) is the CPU's time spent waiting for I/O operations to complete, indicating the percentage of time the CPU is waiting for disk or other I/O device responses.
  • Columns six through eleven (0.00 to 0.00) represent CPU usage in other states, such as the time spent handling hardware or software interrupts and time spent in virtualized environments with CPU steal time.
  • The last column (98.43) indicates the percentage of time the CPU is idle, representing the time when the CPU is not executing any tasks.

In the above example, the CPU usage is as follows:

  • User processes have used 1.31% of CPU time.
  • System kernel processes have used 0.00% of CPU time.
  • There are no "nice" priority processes using CPU time.
  • The CPU is idle for 98.43% of the time.
  • There is no time spent waiting for I/O operations to complete.
  • There is no time spent handling hardware or software interrupts.
  • There is no CPU steal time in a virtualized environment.

Using top command to obtain CPU usage[edit]

  1. Command: Using top command e.g. top on Linux or macOS icon_os_mac.png
  2. Command: Using top command e.g. top -l 2 | grep -E '^CPU' on macOS icon_os_mac.png
  3. Command: Using top command e.g. top -n 1 | grep '%Cpu(s)' on Linux

Example result of top -n 1 | grep '%Cpu(s)'

%Cpu(s):  1.5 us,  1.5 sy,  0.0 ni, 96.9 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st

The result provided is the information about CPU usage obtained through the `top` command. It shows the percentages of different CPU states, and each column is explained as follows:

  • `%Cpu(s)`: This is the header indicating that the following numbers are percentages related to CPU usage.
  • `us` (User): It represents the CPU usage by user-space processes, which includes the percentage of time the CPU is occupied by user programs and processes. In this case, it's 1.5%, indicating that 1.5% of CPU time is used for running user programs.
  • `sy` (System): It represents the CPU usage by system kernel processes, indicating the percentage of time the CPU is occupied by the operating system kernel. In this case, it's 1.5%, indicating that 1.5% of CPU time is used for handling operating system kernel tasks.
  • `ni` (Nice): It represents the CPU usage by processes with a "nice" priority, which includes the percentage of CPU time used by processes adjusted with the `nice` command. In this case, it's 0%, indicating that there are no "nice" processes running.
  • `id` (Idle): It represents the percentage of time the CPU is in an idle state, indicating the percentage of time the CPU is not executing any tasks. In this case, it's 96.9%, meaning that 96.9% of CPU time is idle.
  • `wa` (IO Wait): It represents the CPU usage while waiting for I/O operations to complete, indicating the percentage of time the CPU is waiting for disk or other I/O device responses. In this case, it's 0%, indicating that the CPU is not waiting for I/O to complete.
  • `hi` (Hardware IRQ): It represents the CPU usage caused by hardware interrupts, indicating the percentage of time spent handling hardware device interrupts. In this case, it's 0%, indicating that the CPU is not handling hardware interrupts.
  • `si` (Software IRQ): It represents the CPU usage caused by software interrupts, indicating the percentage of time spent handling software interrupts. In this case, it's 0%, indicating that the CPU is not handling software interrupts.
  • `st` (Steal Time): It represents the "steal time" in a virtualized environment, indicating the percentage of time a virtual machine's CPU is taken away when sharing host CPU resources with other virtual machines. In this case, it's 0%, meaning there is no virtualization steal time.

In summary, this output indicates the following CPU usage:

  • User programs are using 1.5% of CPU time.
  • System kernel tasks are using 1.5% of CPU time.
  • There are no "nice" processes running.
  • 96.9% of CPU time is idle.
  • There is no time spent waiting for I/O operations to complete.
  • There is no time spent handling hardware or software interrupts.
  • There is no virtualization steal time.

System memory usage[edit]

Obtaining Memory Usage through a WQL Query[edit]

on Win :

Obtaining Memory Usage through free command[edit]

on freebsd & Linux

  • command: free
  • output example:
                               total       used       free     shared    buffers     cached
                    Mem:       8060416    7922496     137920        120     183608     526180
                    -/+ buffers/cache:    7212708     847708
                    Swap:      4194300    1219364    2974936
  • memory usage = 7922496 / 8060416; unit: %

Obtaining Memory Usage through top command[edit]

macOS icon_os_mac.png (known as Darwin):

  • command: top -l 1
  • output example: PhysMem: 8017M used (1486M wired), 172M unused.
  • memory usage: 172 / (8017+172); unit: %

Linux or macOS icon_os_mac.png

  • command: top (and press q key to quit the top window)
  • output example: The Python process with the Process ID (PID) 13086 is utilizing 22.19 GB of memory, as indicated by the value in the RES (Resident Set Size) field.
PID    USER      PR  NI  VIRT    RES    SHR S  %CPU %MEM     TIME+   COMMAND
13086 account  20  0   132.1g  22.19g 13.0g S 42.9 17.6     30:33.61 python


  • PID: Process ID, 13086 in this case, which is the unique identifier for the process.
  • USER: The user that started the process, account here.
  • PR: Priority of the process in the kernel's scheduler. The value 20 indicates a regular priority.
  • NI: Nice value, which influences the priority (0 by default, meaning no adjustment to the scheduling).
  • VIRT: Virtual memory size, 132.1g for this process, which is the total amount of virtual memory used by the process.
  • RES: Resident memory size, 22.19g here, showing how much physical memory the process is currently using.
  • SHR: Shared memory size, 13.0g in this case, which is the memory this process is sharing with others.
  • S: Process status, S here which usually means 'sleeping'.
  • %CPU: CPU usage, 42.9 indicating the percentage of the CPU time the process is currently using.
  • %MEM: Memory usage, 17.6 showing the percentage of total physical memory used by the process.
  • TIME+: Total CPU time the process has been running, 30:33.61 indicates 30 minutes and 33.61 seconds.
  • COMMAND: The command that initiated the process, python here.

System disk space usage[edit]

hard disk usage

0M      /sys
1M      /tmp
9M      /run
27M     /etc
36M     /root
165M    /boot
1647M   /usr
49287M  /var
51379M  /home
102547M /

How To Find Largest Top 10 Files and Directories On Linux / UNIX / BSD - nixCraft Icon_exclaim.gif It may costs time to return the result if there are too many file under the specified path. Output example of du -a -BM /path/to/folder/ | sort -n -r | head -n 10:

# du -a -BM /var/ | sort -n -r | head -n 10
11199M  /var/
10384M  /var/lib
6336M   /var/lib/mysql
3714M   /var/lib/strong-pm
3661M   /var/lib/strong-pm/svc
2042M   /var/lib/strong-pm/svc/1/work
2042M   /var/lib/strong-pm/svc/1
1619M   /var/lib/strong-pm/svc/2/work

Options cited from the content of Linux man page<ref>du man page</ref>

  • -a, --all "write counts for all files, not just directories"
  • -B, --block-size=SIZE "scale sizes by SIZE before printing them"

Scan the disk[edit]

Switch the user account[edit]

switch the current user

prints the current user

Clean the screen/console[edit]

help for command[edit]

view the documentation for this command[edit]

  • command --help or man command (Linux )
  • command /? (Win )

find the path of an executable[edit]

emergency exit[edit]

  • ctrl+c or ctrl+break (Linux , Win & macOS icon_os_mac.png )
  • Pause/Break (Linux ) ex: I pressed the key to leave from the warning message "Vim: Warning: Output is not to a terminal".

References[edit]

<references/>

further reading[edit]

related pages: