Difference between revisions of "Core utilities"

From ArchWiki
Jump to: navigation, search
(less)
(ip: use Template:man)
 
(349 intermediate revisions by 46 users not shown)
Line 1: Line 1:
 
[[Category:System administration]]
 
[[Category:System administration]]
[[zh-CN:Core Utilities]]
+
[[Category:Command shells]]
{{Article summary start}}
+
[[fa:Core utilities]]
{{Article summary text|Tips and tricks related to so-called "core" utilities on a GNU/Linux system.}}
+
[[es:Core utilities]]
{{Article summary heading|Related}}
+
[[it:Core utilities]]
{{Article summary wiki|Commandline Tools}}
+
[[ja:Core Utilities]]
{{Article summary wiki|General Recommendations}}
+
[[ko:Core utilities]]
{{Article summary wiki|GNU Project}}
+
[[ru:Core utilities]]
{{Article summary end}}
+
[[zh-cn:Core utilities]]
 +
[[zh-tw:Core utilities]]
 +
{{Related articles start}}
 +
{{Related|Bash}}
 +
{{Related|Zsh}}
 +
{{Related|General recommendations}}
 +
{{Related|GNU Project}}
 +
{{Related|sudo}}
 +
{{Related|cron}}
 +
{{Related|man page}}
 +
{{Related|Securely wipe disk#shred}}
 +
{{Related|File permissions and attributes}}
 +
{{Related|Color output in console}}
 +
{{Related articles end}}
  
This article deals with so-called "core" utilities on a GNU/Linux system, such as '''less''', '''ls''', and '''grep'''. The scope of this article includes -- ''but is not limited to'' -- those utilities included with the GNU {{Pkg|coreutils}} package. What follows are various tips and tricks and other helpful information related to these utilities. If sections grow too detailed, please split into separate articles.
+
This article deals with so-called ''core'' utilities on a GNU/Linux system, such as ''less'', ''ls'', and ''grep''. The scope of this article includes, but is not limited to, those utilities included with the GNU {{Pkg|coreutils}} package. What follows are various tips and tricks and other helpful information related to these utilities.
  
==grep==
+
== Basic commands ==
[[Wikipedia:grep|grep]] is a command line text search utility originally written for Unix. The {{ic|grep}} command searches files or standard input globally for lines matching a given regular expression, and prints them to the program's standard output.
+
  
Beyond aesthetics, {{ic|grep}}'s color output is immensely useful for learning {{ic|regexp}} and {{ic|grep}}'s functionality.
+
The following table lists basic shell commands every Linux user should be familiar with. Commands in '''bold''' are part of the shell, others are separate programs called from the shell. See the below sections and ''Related articles'' for details.
  
To use the default colors for grep, write the following entry to {{ic|~/.bashrc}}:
+
{| class="wikitable"
alias grep='grep --color=auto'
+
! Command
To include file line numbers in the output, add "''-n''":
+
! Description
alias grep='grep -n --color=auto'
+
! Manual page
 +
! Example
 +
|-
 +
| man
 +
| Show manual page for a command
 +
| {{man|7|man}}
 +
| man ed
 +
|-
 +
| '''cd'''
 +
| Change directory
 +
| {{man|1|cd}}
 +
| cd /etc/pacman.d
 +
|-
 +
| mkdir
 +
| Create a directory
 +
| {{man|1|mkdir}}
 +
| mkdir ~/newfolder
 +
|-
 +
| rmdir
 +
| Remove empty directory
 +
| {{man|1|rmdir}}
 +
| rmdir ~/emptyfolder
 +
|-
 +
| rm
 +
| Remove a file
 +
| {{man|1|rm}}
 +
| rm ~/file.txt
 +
|-
 +
| rm -r
 +
| Remove directory and contents
 +
|
 +
| rm -r ~/.cache
 +
|-
 +
| ls
 +
| List files
 +
| {{man|1|ls}}
 +
| ls *.mkv
 +
|-
 +
| ls -a
 +
| List hidden files
 +
|
 +
| ls -a /home/archie
 +
|-
 +
| ls -al
 +
| List hidden files and file properties
 +
|
 +
|
 +
|-
 +
| mv
 +
| Move a file
 +
| {{man|1|mv}}
 +
| mv ~/compressed.zip ~/archive/compressed2.zip
 +
|-
 +
| cp
 +
| Copy a file
 +
| {{man|1|cp}}
 +
| cp ~/.bashrc ~/.bashrc.bak
 +
|-
 +
| chmod +x
 +
| Make a file executable
 +
| {{man|1|chmod}}
 +
| chmod +x ~/.local/bin/myscript.sh
 +
|-
 +
| cat
 +
| Show file contents
 +
| {{man|1|cat}}
 +
| cat /etc/hostname
 +
|-
 +
| strings
 +
| Show printable characters in binary files
 +
| {{man|1|strings}}
 +
| strings /usr/bin/free
 +
|-
 +
| find
 +
| Search for a file
 +
| {{man|1|find}}
 +
| find ~ -name myfile
 +
|-
 +
| mount
 +
| Mount a partition
 +
| {{man|8|mount}}
 +
| mount /dev/sdc1 /media/usb
 +
|-
 +
| df -h
 +
| Show remaining space on all partitions
 +
| {{man|1|df}}
 +
|
 +
|-
 +
| ps -A
 +
| Show all running processes
 +
| {{man|1|ps}}
 +
|
 +
|-
 +
| killall
 +
| Kill all running instances of a process
 +
| {{man|1|killall}}
 +
|
 +
|-
 +
| ss -at
 +
| Display a list of open TCP sockets
 +
| {{man|8|ss}}
 +
|
 +
|}
  
The environment variable {{ic|GREP_COLORS}} may be used to specify different colors than the defaults.
+
== cat ==
  
==less==
+
[[Wikipedia:cat_(Unix)|cat]] is a standard Unix utility that concatenates and lists files.
[[Wikipedia:less (Unix)|less]] is a terminal pager program used to view the contents of a text file one screen at a time. Whilst similar to other pages such as {{ic|more}} and {{ic|pg}}, {{ic|less}} offers a more advanced interface and complete feature-set.[http://www.greenwoodsoftware.com/less/faq.html]
+
  
You can enable code syntax coloring in less. First, install {{Pkg|source-highlight}}.
+
* Because ''cat'' is not a built-in shell, on many occasions you may find it more convenient to use a [[Wikipedia:Redirection (computing)|redirection]], for example in scripts, or if you care a lot about performance. In fact {{ic|< ''file''}} does the same as {{ic|cat ''file''}}.
Then add these lines to your {{ic|~/.bashrc}}:
+
export LESSOPEN="| /usr/bin/source-highlight-esc.sh %s"
+
export LESS=' -R '
+
  
 +
* ''cat'' is able to work with multiple lines:
  
Frequent users of the command line interface might want to install {{Pkg|lesspipe}}:
+
{{bc|
# pacman -S lesspipe
+
$ cat << EOF >> ''path/file''
 +
''first line''
 +
...
 +
''last line''
 +
EOF
 +
}}
  
Users may now list the compressed files inside of an archive using their pager:
+
Alternatively, using {{ic|printf}}:
  
{{hc
+
{{bc|
|$ less compressed_file.tar.gz
+
$ printf '%s\n' 'first line' ... 'last line'
|<nowiki>
+
}}
==> use tar_file:contained_file to view a file in the archive
+
-rw------- username/group  695 2008-01-04 19:24 compressed_file/content1
+
-rw------- username/group  43 2007-11-07 11:17 compressed_file/content2
+
compressed_file.tar.gz (END)
+
</nowiki>}}
+
  
{{ic|lesspipe}} also grants {{ic|less}} the ability of interfacing with files other than archives; serving as an alternative for the specific command associated for that file-type (such as viewing HTML via {{Pkg|html2text}}).
+
* If you need to list file lines in reverse order, there is a utility called [[Wikipedia:tac (Unix)|tac]] (''cat'' reversed).
  
Re-login after installing {{ic|lesspipe}} in order to activate it, or source {{ic|/etc/profile.d/lesspipe.sh}}.
+
== dd ==
  
==ls==
+
[[Wikipedia:dd (Unix)|dd]] is a utility for Unix and Unix-like operating systems whose primary purpose is to convert and copy a file.
[[Wikipedia:ls|ls]] is a command to list files in Unix and Unix-like operating systems.
+
  
Colored output can be enabled with a simple alias. File {{ic|~/.bashrc}} should already have the following entry copied from {{ic|/etc/skel/.bashrc}}:
+
Similarly to ''cp'', by default ''dd'' makes a bit-to-bit copy of the file, but with lower-level I/O flow control features.
alias ls='ls --color=auto'
+
  
The next step will further enhance the colored {{ic|ls}} output; for example, broken (orphan) symlinks will start showing in a red hue. Add the following to {{ic|~/.bashrc}} and relogin, or source the file:
+
{{Tip|By default, ''dd'' outputs nothing until the task has finished. To monitor the progress of the operation, add the {{ic|1=status=progress}} option to the command.}}
  eval $(dircolors -b)
+
 
 +
'dd' can be used to:
 +
* [[Disk_cloning#Using_dd|drive-related]] tasks:
 +
** Create an image.
 +
** Write an image.
 +
** Clone whole drive, or partition.
 +
** Wipe drive or partition.
 +
** Erase partition table or boot sector.
 +
** Backup boot sector.
 +
** Restore system.
 +
* Get stream from device, {{ic|dd /dev/random}}, or some input device.
 +
* Create load on CPU (example: {{ic|1=dd if=/dev/zero of=/dev/null}}).
 +
* Create load on disk (example: {{ic|1=dd if=/dev/zero of=/''path''/''testfile'' bs=''number_of''G count=''times'' oflag=''fdatasync''}}).
 +
* Create I/O load on disk (many rapid read/writes) (example above with little block size ({{ic|bs}}) and big amount of cycles ({{ic|count}}) and needed {{ic|oflag}}, based on what and how you want to test).
 +
* As a backup utility or part of solution.
 +
* Convert a file to upper/lower case.
 +
 
 +
For more information see {{man|1|dd}} or the [http://www.gnu.org/software/coreutils/dd full documentation].
 +
 
 +
== grep ==
 +
 
 +
[[Wikipedia:grep|grep]] (from [[Wikipedia:ed|ed]]'s ''g/re/p'', ''global/regular expression/print'') is a command line text search utility originally written for Unix. The ''grep'' command searches files or standard input for lines matching a given regular expression, and prints these lines to the program's standard output.
 +
 
 +
* Remember that ''grep'' handles files, so a construct like {{ic|cat ''file'' <nowiki>|</nowiki> grep ''pattern''}} is replaceable with {{ic|grep ''pattern'' ''file''}}
 +
* There are ''grep'' alternatives optimized for VCS source code, such as {{Pkg|the_silver_searcher}} and {{Pkg|ack}}.
 +
* To include file line numbers in the output, use the {{ic|-n}} option.
 +
 
 +
{{Note|Some commands send their output to {{man|3|stderr}}, and grep has no apparent effect. In this case, redirect ''stderr'' to ''stdout'' with {{ic|''command'' 2>&1 {{!}} grep ''args''}} or (for Bash 4) {{ic|''command'' {{!}}& grep ''args''}}. See also [http://www.tldp.org/LDP/abs/html/io-redirection.html I/O Redirection].}}
 +
 
 +
For color support, see [[Color output in console#grep]].
 +
 
 +
== find ==
 +
 
 +
''find'' is part of the {{Pkg|findutils}} package, which belongs to the {{Grp|base}} package group.
 +
 
 +
One would probably expect a ''find'' command to take as argument a file name and search the filesystem for files matching that name. For a program that does exactly that see [[#locate]] below.
 +
 
 +
Instead, find takes a set of directories and matches each file under them against a set of expressions. This design allows for some very powerful "one-liners" that would not be possible using the "intuitive" design described above. See [http://mywiki.wooledge.org/UsingFind UsingFind] for usage details.
 +
 
 +
== iconv ==
 +
 
 +
''iconv'' converts the encoding of characters from one codeset to another.
 +
 
 +
The following command will convert the file {{ic|foo}} from ISO-8859-15 to UTF-8 saving it to {{ic|foo.utf}}:
 +
 
 +
$ iconv -f ISO-8859-15 -t UTF-8 foo >foo.utf
 +
 
 +
See {{ic|man iconv}} for more details.
 +
 
 +
=== Convert a file in place ===
 +
 
 +
{{Tip|You can use {{pkg|recode}} instead of iconv if you do not want to touch the mtime.}}
 +
Unlike [[#sed|sed]], ''iconv'' does not provide an option to convert a file in place. However, {{ic|sponge}} can be used to handle it, it comes with {{pkg|moreutils}}.
 +
 
 +
$ iconv -f WINDOWS-1251 -t UTF-8 foobar.txt | sponge foobar.txt
 +
 
 +
See {{ic|man sponge}} for details.
 +
 
 +
== ip ==
 +
 
 +
[[Wikipedia:Iproute2|ip]] allows you to show information about network devices, IP addresses, routing tables, and other objects in the Linux [[Wikipedia:Internet Protocol|IP]] software stack. By appending various commands, you can also manipulate or configure most of these objects.
 +
 
 +
{{Note|The ''ip'' utility is provided by the {{Pkg|iproute2}} package, which is included in the {{Grp|base}} group.}}
 +
 
 +
{| class="wikitable"
 +
! Object !! Purpose !! Manual page
 +
|-
 +
| ip addr || protocol address management || {{man|8|ip-address|url=}}
 +
|-
 +
| ip addrlabel || protocol address label management || {{man|8|ip-addrlabel}}
 +
|-
 +
| ip l2tp || tunnel Ethernet over IP (L2TPv3) || {{man|8|ip-l2tp}}
 +
|-
 +
| ip link || network device configuration || {{man|8|ip-link|url=}}
 +
|-
 +
| ip maddr || multicast addresses management || {{man|8|ip-maddress}}
 +
|-
 +
| ip monitor || watch for netlink messages || {{man|8|ip-monitor}}
 +
|-
 +
| ip mroute || multicast routing cache management || {{man|8|ip-mroute}}
 +
|-
 +
| ip mrule || rule in multicast routing policy db ||
 +
|-
 +
| ip neigh || neighbour/ARP tables management || {{man|8|ip-neighbour}}
 +
|-
 +
| ip netns || process network namespace management || {{man|8|ip-netns}}
 +
|-
 +
| ip ntable || neighbour table configuration || {{man|8|ip-ntable}}
 +
|-
 +
| ip route || routing table management || {{man|8|ip-route|url=}}
 +
|-
 +
| ip rule || routing policy database management || {{man|8|ip-rule}}
 +
|-
 +
| ip tcp_metrics || management for TCP Metrics || {{man|8|ip-tcp_metrics}}
 +
|-
 +
| ip tunnel || tunnel configuration || {{man|8|ip-tunnel}}
 +
|-
 +
| ip tuntap || manage TUN/TAP devices ||
 +
|-
 +
| ip xfrm || manage IPsec policies || {{man|8|ip-xfrm}}
 +
|}
 +
 
 +
The {{ic|help}} command is available for all objects. For example, typing {{ic|ip addr help}} will show you the command syntax available for the address object. For advanced usage see the [http://www.policyrouting.org/iproute2.doc.html iproute2 documentation].
 +
 
 +
The [[Network configuration]] article shows how the ''ip'' command is used in practice for various common tasks.
 +
 
 +
{{Note|You might be familiar with the [[Wikipedia:ifconfig|ifconfig]] command, which was used in older versions of Linux for interface configuration. It is now deprecated in Arch Linux; you should use ''ip'' instead. }}
 +
 
 +
== locate ==
 +
 
 +
[[Install]] the {{Pkg|mlocate}} package. After installation a script is automatically scheduled to run a daily task to update its database. You can also manually run ''updatedb'' as root at any time. By default, paths such as {{ic|/media}} and {{ic|/mnt}} are ignored, so ''locate'' may not discover files on external devices. See {{man|1| updatedb}} for details.
 +
 
 +
The ''locate'' command is a common Unix tool for quickly finding files by name. It offers speed improvements over the [[wikipedia:Find|find]] tool by searching a pre-constructed database file, rather than the filesystem directly. The downside of this approach is that changes made since the construction of the database file cannot be detected by ''locate''. This problem is minimised by regular, typically scheduled use of the ''updatedb'' command, which (as the name suggests) updates the database.
 +
 
 +
Before ''locate'' can be used, the database will need to be created. To do this, execute {{ic|updatedb}} as root.
 +
 
 +
See also [http://jvns.ca/blog/2015/03/05/how-the-locate-command-works-and-lets-rewrite-it-in-one-minute/ How locate works and rewrite it in one minute].
 +
 
 +
== less ==
 +
 
 +
{{Expansion|less is a complex beast, and this section should explain some of the basic less commands}}
 +
 
 +
[[Wikipedia:less (Unix)|less]] is a terminal pager program used to view the contents of a text file one screen at a time. Whilst similar to other pagers such as [[Wikipedia:more (command)|more]] and [[Wikipedia:pg (Unix)|pg]], ''less'' offers a more advanced interface and complete [http://www.greenwoodsoftware.com/less/faq.html feature-set].
 +
 
 +
See [[List of applications#Terminal pagers]] for alternatives.
 +
 
 +
=== Vim as alternative pager ===
 +
 
 +
[[Vim]] includes a script to view the content of text files, compressed files, binaries, directories. Add the following line to your shell configuration file to use it as a pager:
 +
{{hc|~/.bashrc|2=alias less='/usr/share/vim/vim74/macros/less.sh'}}
 +
 
 +
There is also an alternative to ''less.sh'' macro, which may work as the {{ic|PAGER}} environment variable. Install {{Pkg|vimpager}} and add the following to your shell configuration file:
 +
{{hc|~/.bashrc|2=
 +
export PAGER='vimpager'
 +
alias less=$PAGER
 +
}}
 +
 
 +
Now programs that use the {{ic|PAGER}} environment variable, like [[git]], will use ''vim'' as pager.
 +
 
 +
== ls ==
 +
 
 +
[[Wikipedia:ls|ls]] lists directory contents.
 +
 
 +
See {{ic|info ls}} or [http://www.gnu.org/software/coreutils/manual/html_node/ls-invocation.html#ls-invocation the online manual] for more information.
 +
 
 +
=== Long format ===
 +
 
 +
The {{ic|-l}} option displays some metadata, for example:
 +
 
 +
{{hc|$ ls -l /path/to/directory|
 +
total 128
 +
drwxr-xr-x 2 archie users  4096 Jul  5 21:03 Desktop
 +
drwxr-xr-x 6 archie users  4096 Jul  5 17:37 Documents
 +
drwxr-xr-x 2 archie users  4096 Jul  5 13:45 Downloads
 +
-rw-rw-r-- 1 archie users  5120 Jun 27 08:28 customers.ods
 +
-rw-r--r-- 1 archie users  3339 Jun 27 08:28 todo
 +
-rwxr-xr-x 1 archie users  2048 Jul  6 12:56 myscript.sh
 +
}}
 +
 
 +
The {{ic|total}} value represents the total disk allocation for the files in the directory, by default in number of blocks.
 +
 
 +
Below, each file and subdirectory is represented by a line divided into 7 metadata fields, in the following order:
 +
 
 +
* type and permissions:
 +
** the first character is the entry type, see {{ic|info ls -n "What information is listed"}} for an explanation of all the possible types; for example:
 +
*** {{ic|-}} denotes a normal file;
 +
*** {{ic|d}} denotes a directory, i.e. a folder containing other files or folders;
 +
*** {{ic|p}} denotes a named pipe (aka FIFO);
 +
*** {{ic|l}} denotes a symbolic link;
 +
** the remaining characters are the entry's [[permissions]];
 +
* number of [[Wikipedia:Hard link|hard links]] for the entity; files will have at least 1, i.e. the showed reference itself; folders will have at least 2: the showed reference, the self-referencing {{ic|.}} entry, and then a {{ic|..}} entry in each of its subfolders;
 +
* owner [[user]] name;
 +
* [[group]] name;
 +
* size;
 +
* last modification timestamp;
 +
* entity name.
 +
 
 +
=== File names containing spaces enclosed in quotes ===
 +
 
 +
By default, file and directory names that contain spaces are displayed surrounded by single quotes. To change this behavior use the {{ic|-N}} or {{ic|1=--quoting-style=literal}} options. Alternatively, set the {{ic|QUOTING_STYLE}} [[environment variable]] to {{ic|literal}}. [https://unix.stackexchange.com/questions/258679/why-is-ls-suddenly-surrounding-items-with-spaces-in-single-quotes]
 +
 
 +
== lsblk ==
 +
 
 +
{{man|8|lsblk}} will show all available [[w:Device_file#Block_devices|block devices]] along with their partitioning schemes, for example:
 +
 
 +
{{hc|$ lsblk -f|
 +
NAME  FSTYPE  LABEL      UUID                                MOUNTPOINT
 +
sda
 +
├─sda1 vfat                C4DA-2C4D                            /boot
 +
├─sda2 swap                5b1564b2-2e2c-452c-bcfa-d1f572ae99f2 [SWAP]
 +
└─sda3 ext4                56adc99b-a61e-46af-aab7-a6d07e504652 /
 +
}}
 +
 
 +
The beginning of the device name specifies the type of block device. Most modern storage devices (e.g. hard disks, [[SSD]]s and USB flash drives) are recognised as SCSI disks ({{ic|sd}}). The type is followed by a lower-case letter starting from {{ic|a}} for the first device ({{ic|sda}}), {{ic|b}} for the second device ({{ic|sdb}}), and so on. ''Existing'' partitions on each device will be listed with a number starting from {{ic|1}} for the first partition ({{ic|sda1}}), {{ic|2}} for the second ({{ic|sda2}}), and so on. In the example above, only one device is available ({{ic|sda}}), and that device has three partitions ({{ic|sda1}} to {{ic|sda3}}), each with a different [[file system]].
 +
 
 +
Other common block device types include for example {{ic|mmcblk}} for memory cards and {{ic|nvme}} for [[Solid_State_Drives/NVMe|NVMe]] devices. Unknown types can be searched in the [https://www.kernel.org/doc/Documentation/devices.txt kernel documentation].
 +
 
 +
== mkdir ==
 +
 
 +
[[Wikipedia:mkdir|mkdir]] makes directories.
 +
 
 +
To create a directory and its whole hierarchy, the {{ic|-p}} switch is used, otherwise an error is printed. As users are supposed to know what they want, {{ic|-p}} switch may be used as a default:
 +
 
 +
alias mkdir='mkdir -p -v'
 +
 
 +
The {{ic|-v}} switch make it verbose.
 +
 
 +
Changing mode of a just created directory using ''chmod'' is not necessary as the {{ic|-m}} option lets you define the access permissions.
 +
 
 +
{{Tip|If you just want a temporary directory, a better alternative may be [[Wikipedia:Temporary file|mktemp]]: {{ic|mktemp -p}}.}}
 +
 
 +
== mv ==
 +
 
 +
[[Wikipedia:mv|mv]] moves and renames files and directories.
 +
 
 +
To limit potential damage caused by the command, use an alias:
 +
 
 +
alias mv='timeout 8 mv -iv'
 +
 
 +
This alias suspends ''mv'' after eight seconds, asks confirmation to delete three or more files, lists the operations in progress and does not store itself in the shell history file if the shell is configured to ignore space starting commands.
 +
 
 +
== od ==
 +
 
 +
The [[Wikipedia:od (Unix)|od]] (''o''ctal ''d''ump) command is useful for visualizing data that is not in a human-readable format, like the executable code of a program, or the contents of an unformatted device. See the [http://www.gnu.org/software/coreutils/manual/html_node/od-invocation.html#od-invocation manual] for more information.
 +
 
 +
== pv ==
 +
 
 +
You can use {{Pkg|pv}} (''pipe viewer'') to monitor the progress of data through a pipeline, for example:
 +
 
 +
# dd if=''/source/filestream'' | pv -''monitor_options'' -s ''size_of_file'' | dd of=''/destination/filestream''
 +
 
 +
In most cases {{ic|pv}} functions as a drop-in replacement for {{ic|cat}}.
 +
 
 +
== rm ==
 +
 
 +
[[Wikipedia:rm_(Unix)|rm]] removes files or directories.
 +
 
 +
To limit potential damage caused by the command, use an alias:
 +
 
 +
alias rm='timeout 3 rm -Iv --one-file-system'
 +
 
 +
This alias suspends ''rm'' after three seconds, asks confirmation to delete three or more files, lists the operations in progress, does not involve more than one file systems and does not store itself in the shell history file if the shell is configured to ignore space starting commands. Substitute {{ic|-I}} with {{ic|-i}} if you prefer to confirm even for one file.
 +
 
 +
Zsh users may want to put {{ic|noglob}} before {{ic|timeout}} to avoid implicit expansions.
 +
 
 +
To remove directories known to be empty, use ''rmdir'' as it fails in case of files inside the target.
 +
 
 +
== sed ==
 +
 
 +
[[Wikipedia:sed|sed]] is stream editor for filtering and transforming text.
 +
 
 +
Here is a handy [http://sed.sourceforge.net/sed1line.txt list] of ''sed'' one-liners examples.
 +
 
 +
{{Tip|More powerful alternatives are [[Wikipedia:AWK|AWK]] and even [[Wikipedia:Perl|Perl]] language.}}
 +
 
 +
== seq ==
 +
 
 +
''seq'' prints a sequence of numbers. Shell built-in alternatives are available, so it is good practice to use them as explained on [[Wikipedia:Seq (Unix)|Wikipedia]].
 +
 
 +
== ss ==
 +
 
 +
''ss'' is a utility to investigate network ports and is part of the {{Pkg|iproute2}} package in the {{Grp|base}} group. It has a similar functionality to the [https://www.archlinux.org/news/deprecation-of-net-tools/ deprecated] netstat utility.
 +
 
 +
Common usage includes:
 +
 
 +
Display all TCP Sockets with service names:
 +
  $ ss -at
 +
 
 +
Display all TCP Sockets with port numbers:
 +
$ ss -atn
 +
 
 +
Display all UDP Sockets:
 +
$ ss -au
 +
 
 +
For more information see {{man|8|ss}} or [http://www.cyberciti.biz/files/ss.html introductory examples].
 +
 
 +
== tar ==
 +
 
 +
As an early Unix archiving format, .tar files—known as "tarballs"—are widely used for packaging in Unix-like operating systems. Both [[pacman]] and [[AUR]] packages are compressed tarballs, and Arch uses [[GNU Project|GNU's]] ''tar'' program by default.
 +
 
 +
For .tar archives, ''tar'' by default will extract the file according to its extension:
 +
 
 +
$ tar xvf ''file.EXTENSION''
 +
 
 +
Forcing a given format:
 +
 
 +
{| class="wikitable"
 +
!File Type    !! Extraction Command
 +
|-
 +
|{{ic|''file''.tar}}    || {{Ic|tar xvf ''file''.tar}}
 +
|-
 +
|{{ic|''file''.tgz}}    || {{Ic|tar xvzf ''file''.tgz}}
 +
|-
 +
|{{ic|''file''.tar.gz}}  || {{Ic|tar xvzf ''file''.tar.gz}}
 +
|-
 +
|{{ic|''file''.tar.bz}}  || {{Ic|bzip -cd ''file''.bz <nowiki>|</nowiki> tar xvf -}}
 +
|-
 +
|{{ic|''file''.tar.bz2}} || {{Ic|tar xvjf ''file''.tar.bz2}}<br> {{Ic|bzip2 -cd ''file''.bz2 <nowiki>| tar xvf -</nowiki>}}
 +
|-
 +
|{{ic|''file''.tar.xz}}  || {{Ic|tar xvJf ''file''.tar.xz}}<br> {{Ic|xz -cd ''file''.xz <nowiki>| tar xvf -</nowiki>}}
 +
|}
 +
 
 +
The construction of some of these ''tar'' arguments may be considered legacy, but they are still useful when performing specific operations. See its [[man page]] with {{ic|man tar}} for details.
 +
 
 +
== which ==
 +
 
 +
[[wikipedia:Which_(Unix)|which]] shows the full path of shell commands. In the following example the full path of {{ic|ssh}} is used as an argument for {{ic|journalctl}}:
 +
 
 +
# journalctl $(which sshd)
 +
 
 +
== wipefs ==
 +
 
 +
''wipefs'' can list or erase [[file system]], [[RAID]] or [[partition|partition-table]] signatures (magic strings) from the specified device. It does not erase the file systems themselves nor any other data from the device.
 +
 
 +
See {{man|8|wipefs}} for more information.
 +
 
 +
For example, to erase all signatures from the device {{ic|/dev/sdb}} and create a signature backup {{ic|~/wipefs-sdb-''offset''.bak}} file for each signature:
 +
 
 +
# wipefs --all --backup /dev/sdb
 +
 
 +
== See also ==
 +
 
 +
* [http://www.reddit.com/r/commandline/comments/19garq/a_sampling_of_coreutils_120/ A sampling of coreutils] [http://www.reddit.com/r/commandline/comments/19ge6v/a_sampling_of_coreutils_2040/ , part 2] [http://www.reddit.com/r/commandline/comments/19j1w3/a_sampling_of_coreutils_4060/ , part 3] - Overview of commands in coreutils
 +
* [http://www.gnu.org/software/coreutils/manual/coreutils.html GNU Coreutils online documentation]
 +
* [http://www.linuxquestions.org/questions/linux-newbie-8/learn-the-dd-command-362506/ Learn the DD command]

Latest revision as of 16:18, 20 September 2016

This article deals with so-called core utilities on a GNU/Linux system, such as less, ls, and grep. The scope of this article includes, but is not limited to, those utilities included with the GNU coreutils package. What follows are various tips and tricks and other helpful information related to these utilities.

Basic commands

The following table lists basic shell commands every Linux user should be familiar with. Commands in bold are part of the shell, others are separate programs called from the shell. See the below sections and Related articles for details.

Command Description Manual page Example
man Show manual page for a command man(7) man ed
cd Change directory cd(1) cd /etc/pacman.d
mkdir Create a directory mkdir(1) mkdir ~/newfolder
rmdir Remove empty directory rmdir(1) rmdir ~/emptyfolder
rm Remove a file rm(1) rm ~/file.txt
rm -r Remove directory and contents rm -r ~/.cache
ls List files ls(1) ls *.mkv
ls -a List hidden files ls -a /home/archie
ls -al List hidden files and file properties
mv Move a file mv(1) mv ~/compressed.zip ~/archive/compressed2.zip
cp Copy a file cp(1) cp ~/.bashrc ~/.bashrc.bak
chmod +x Make a file executable chmod(1) chmod +x ~/.local/bin/myscript.sh
cat Show file contents cat(1) cat /etc/hostname
strings Show printable characters in binary files strings(1) strings /usr/bin/free
find Search for a file find(1) find ~ -name myfile
mount Mount a partition mount(8) mount /dev/sdc1 /media/usb
df -h Show remaining space on all partitions df(1)
ps -A Show all running processes ps(1)
killall Kill all running instances of a process killall(1)
ss -at Display a list of open TCP sockets ss(8)

cat

cat is a standard Unix utility that concatenates and lists files.

  • Because cat is not a built-in shell, on many occasions you may find it more convenient to use a redirection, for example in scripts, or if you care a lot about performance. In fact < file does the same as cat file.
  • cat is able to work with multiple lines:
$ cat << EOF >> path/file
first line
...
last line
EOF

Alternatively, using printf:

$ printf '%s\n' 'first line' ... 'last line'
  • If you need to list file lines in reverse order, there is a utility called tac (cat reversed).

dd

dd is a utility for Unix and Unix-like operating systems whose primary purpose is to convert and copy a file.

Similarly to cp, by default dd makes a bit-to-bit copy of the file, but with lower-level I/O flow control features.

Tip: By default, dd outputs nothing until the task has finished. To monitor the progress of the operation, add the status=progress option to the command.

'dd' can be used to:

  • drive-related tasks:
    • Create an image.
    • Write an image.
    • Clone whole drive, or partition.
    • Wipe drive or partition.
    • Erase partition table or boot sector.
    • Backup boot sector.
    • Restore system.
  • Get stream from device, dd /dev/random, or some input device.
  • Create load on CPU (example: dd if=/dev/zero of=/dev/null).
  • Create load on disk (example: dd if=/dev/zero of=/path/testfile bs=number_ofG count=times oflag=fdatasync).
  • Create I/O load on disk (many rapid read/writes) (example above with little block size (bs) and big amount of cycles (count) and needed oflag, based on what and how you want to test).
  • As a backup utility or part of solution.
  • Convert a file to upper/lower case.

For more information see dd(1) or the full documentation.

grep

grep (from ed's g/re/p, global/regular expression/print) is a command line text search utility originally written for Unix. The grep command searches files or standard input for lines matching a given regular expression, and prints these lines to the program's standard output.

  • Remember that grep handles files, so a construct like cat file | grep pattern is replaceable with grep pattern file
  • There are grep alternatives optimized for VCS source code, such as the_silver_searcher and ack.
  • To include file line numbers in the output, use the -n option.
Note: Some commands send their output to stderr(3), and grep has no apparent effect. In this case, redirect stderr to stdout with command 2>&1 | grep args or (for Bash 4) command |& grep args. See also I/O Redirection.

For color support, see Color output in console#grep.

find

find is part of the findutils package, which belongs to the base package group.

One would probably expect a find command to take as argument a file name and search the filesystem for files matching that name. For a program that does exactly that see #locate below.

Instead, find takes a set of directories and matches each file under them against a set of expressions. This design allows for some very powerful "one-liners" that would not be possible using the "intuitive" design described above. See UsingFind for usage details.

iconv

iconv converts the encoding of characters from one codeset to another.

The following command will convert the file foo from ISO-8859-15 to UTF-8 saving it to foo.utf:

$ iconv -f ISO-8859-15 -t UTF-8 foo >foo.utf

See man iconv for more details.

Convert a file in place

Tip: You can use recode instead of iconv if you do not want to touch the mtime.

Unlike sed, iconv does not provide an option to convert a file in place. However, sponge can be used to handle it, it comes with moreutils.

$ iconv -f WINDOWS-1251 -t UTF-8 foobar.txt | sponge foobar.txt

See man sponge for details.

ip

ip allows you to show information about network devices, IP addresses, routing tables, and other objects in the Linux IP software stack. By appending various commands, you can also manipulate or configure most of these objects.

Note: The ip utility is provided by the iproute2 package, which is included in the base group.
Object Purpose Manual page
ip addr protocol address management ip-address(8)
ip addrlabel protocol address label management ip-addrlabel(8)
ip l2tp tunnel Ethernet over IP (L2TPv3) ip-l2tp(8)
ip link network device configuration ip-link(8)
ip maddr multicast addresses management ip-maddress(8)
ip monitor watch for netlink messages ip-monitor(8)
ip mroute multicast routing cache management ip-mroute(8)
ip mrule rule in multicast routing policy db
ip neigh neighbour/ARP tables management ip-neighbour(8)
ip netns process network namespace management ip-netns(8)
ip ntable neighbour table configuration ip-ntable(8)
ip route routing table management ip-route(8)
ip rule routing policy database management ip-rule(8)
ip tcp_metrics management for TCP Metrics ip-tcp_metrics(8)
ip tunnel tunnel configuration ip-tunnel(8)
ip tuntap manage TUN/TAP devices
ip xfrm manage IPsec policies ip-xfrm(8)

The help command is available for all objects. For example, typing ip addr help will show you the command syntax available for the address object. For advanced usage see the iproute2 documentation.

The Network configuration article shows how the ip command is used in practice for various common tasks.

Note: You might be familiar with the ifconfig command, which was used in older versions of Linux for interface configuration. It is now deprecated in Arch Linux; you should use ip instead.

locate

Install the mlocate package. After installation a script is automatically scheduled to run a daily task to update its database. You can also manually run updatedb as root at any time. By default, paths such as /media and /mnt are ignored, so locate may not discover files on external devices. See updatedb(1) for details.

The locate command is a common Unix tool for quickly finding files by name. It offers speed improvements over the find tool by searching a pre-constructed database file, rather than the filesystem directly. The downside of this approach is that changes made since the construction of the database file cannot be detected by locate. This problem is minimised by regular, typically scheduled use of the updatedb command, which (as the name suggests) updates the database.

Before locate can be used, the database will need to be created. To do this, execute updatedb as root.

See also How locate works and rewrite it in one minute.

less

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: less is a complex beast, and this section should explain some of the basic less commands (Discuss in Talk:Core utilities#)
less is a terminal pager program used to view the contents of a text file one screen at a time. Whilst similar to other pagers such as more and pg, less offers a more advanced interface and complete feature-set.

See List of applications#Terminal pagers for alternatives.

Vim as alternative pager

Vim includes a script to view the content of text files, compressed files, binaries, directories. Add the following line to your shell configuration file to use it as a pager:

~/.bashrc
alias less='/usr/share/vim/vim74/macros/less.sh'

There is also an alternative to less.sh macro, which may work as the PAGER environment variable. Install vimpager and add the following to your shell configuration file:

~/.bashrc
export PAGER='vimpager'
alias less=$PAGER

Now programs that use the PAGER environment variable, like git, will use vim as pager.

ls

ls lists directory contents.

See info ls or the online manual for more information.

Long format

The -l option displays some metadata, for example:

$ ls -l /path/to/directory
total 128
drwxr-xr-x 2 archie users  4096 Jul  5 21:03 Desktop
drwxr-xr-x 6 archie users  4096 Jul  5 17:37 Documents
drwxr-xr-x 2 archie users  4096 Jul  5 13:45 Downloads
-rw-rw-r-- 1 archie users  5120 Jun 27 08:28 customers.ods
-rw-r--r-- 1 archie users  3339 Jun 27 08:28 todo
-rwxr-xr-x 1 archie users  2048 Jul  6 12:56 myscript.sh

The total value represents the total disk allocation for the files in the directory, by default in number of blocks.

Below, each file and subdirectory is represented by a line divided into 7 metadata fields, in the following order:

  • type and permissions:
    • the first character is the entry type, see info ls -n "What information is listed" for an explanation of all the possible types; for example:
      • - denotes a normal file;
      • d denotes a directory, i.e. a folder containing other files or folders;
      • p denotes a named pipe (aka FIFO);
      • l denotes a symbolic link;
    • the remaining characters are the entry's permissions;
  • number of hard links for the entity; files will have at least 1, i.e. the showed reference itself; folders will have at least 2: the showed reference, the self-referencing . entry, and then a .. entry in each of its subfolders;
  • owner user name;
  • group name;
  • size;
  • last modification timestamp;
  • entity name.

File names containing spaces enclosed in quotes

By default, file and directory names that contain spaces are displayed surrounded by single quotes. To change this behavior use the -N or --quoting-style=literal options. Alternatively, set the QUOTING_STYLE environment variable to literal. [1]

lsblk

lsblk(8) will show all available block devices along with their partitioning schemes, for example:

$ lsblk -f
NAME   FSTYPE   LABEL       UUID                                 MOUNTPOINT
sda
├─sda1 vfat                 C4DA-2C4D                            /boot
├─sda2 swap                 5b1564b2-2e2c-452c-bcfa-d1f572ae99f2 [SWAP]
└─sda3 ext4                 56adc99b-a61e-46af-aab7-a6d07e504652 /

The beginning of the device name specifies the type of block device. Most modern storage devices (e.g. hard disks, SSDs and USB flash drives) are recognised as SCSI disks (sd). The type is followed by a lower-case letter starting from a for the first device (sda), b for the second device (sdb), and so on. Existing partitions on each device will be listed with a number starting from 1 for the first partition (sda1), 2 for the second (sda2), and so on. In the example above, only one device is available (sda), and that device has three partitions (sda1 to sda3), each with a different file system.

Other common block device types include for example mmcblk for memory cards and nvme for NVMe devices. Unknown types can be searched in the kernel documentation.

mkdir

mkdir makes directories.

To create a directory and its whole hierarchy, the -p switch is used, otherwise an error is printed. As users are supposed to know what they want, -p switch may be used as a default:

alias mkdir='mkdir -p -v'

The -v switch make it verbose.

Changing mode of a just created directory using chmod is not necessary as the -m option lets you define the access permissions.

Tip: If you just want a temporary directory, a better alternative may be mktemp: mktemp -p.

mv

mv moves and renames files and directories.

To limit potential damage caused by the command, use an alias:

alias mv='timeout 8 mv -iv'

This alias suspends mv after eight seconds, asks confirmation to delete three or more files, lists the operations in progress and does not store itself in the shell history file if the shell is configured to ignore space starting commands.

od

The od (octal dump) command is useful for visualizing data that is not in a human-readable format, like the executable code of a program, or the contents of an unformatted device. See the manual for more information.

pv

You can use pv (pipe viewer) to monitor the progress of data through a pipeline, for example:

# dd if=/source/filestream | pv -monitor_options -s size_of_file | dd of=/destination/filestream

In most cases pv functions as a drop-in replacement for cat.

rm

rm removes files or directories.

To limit potential damage caused by the command, use an alias:

alias rm='timeout 3 rm -Iv --one-file-system'

This alias suspends rm after three seconds, asks confirmation to delete three or more files, lists the operations in progress, does not involve more than one file systems and does not store itself in the shell history file if the shell is configured to ignore space starting commands. Substitute -I with -i if you prefer to confirm even for one file.

Zsh users may want to put noglob before timeout to avoid implicit expansions.

To remove directories known to be empty, use rmdir as it fails in case of files inside the target.

sed

sed is stream editor for filtering and transforming text.

Here is a handy list of sed one-liners examples.

Tip: More powerful alternatives are AWK and even Perl language.

seq

seq prints a sequence of numbers. Shell built-in alternatives are available, so it is good practice to use them as explained on Wikipedia.

ss

ss is a utility to investigate network ports and is part of the iproute2 package in the base group. It has a similar functionality to the deprecated netstat utility.

Common usage includes:

Display all TCP Sockets with service names:

$ ss -at

Display all TCP Sockets with port numbers:

$ ss -atn

Display all UDP Sockets:

$ ss -au

For more information see ss(8) or introductory examples.

tar

As an early Unix archiving format, .tar files—known as "tarballs"—are widely used for packaging in Unix-like operating systems. Both pacman and AUR packages are compressed tarballs, and Arch uses GNU's tar program by default.

For .tar archives, tar by default will extract the file according to its extension:

$ tar xvf file.EXTENSION

Forcing a given format:

File Type Extraction Command
file.tar tar xvf file.tar
file.tgz tar xvzf file.tgz
file.tar.gz tar xvzf file.tar.gz
file.tar.bz bzip -cd file.bz | tar xvf -
file.tar.bz2 tar xvjf file.tar.bz2
bzip2 -cd file.bz2 | tar xvf -
file.tar.xz tar xvJf file.tar.xz
xz -cd file.xz | tar xvf -

The construction of some of these tar arguments may be considered legacy, but they are still useful when performing specific operations. See its man page with man tar for details.

which

which shows the full path of shell commands. In the following example the full path of ssh is used as an argument for journalctl:

# journalctl $(which sshd)

wipefs

wipefs can list or erase file system, RAID or partition-table signatures (magic strings) from the specified device. It does not erase the file systems themselves nor any other data from the device.

See wipefs(8) for more information.

For example, to erase all signatures from the device /dev/sdb and create a signature backup ~/wipefs-sdb-offset.bak file for each signature:

# wipefs --all --backup /dev/sdb

See also