Docs/Drafts/CommandLineSurvivalGuide/CommonlyUsedCommands

From FedoraProject

Jump to: navigation, search
Warning (medium size).png
This page is a draft only
It is still under construction and content may change. Do not rely on the information on this page.

Contents

Commonly Used Commands

This list would include the commands introduced in the handling of scenarios. The purpose would be to combine the options and summarize the use of the commands into one place for easy reference.

The intent is not to reproduce man pages or any other information, but to describe the commonly used options and to provide a pointer to more information.

This list is my best guess at the commands, but it would need to be checked against the scenarios that are described.

  • basename
  • bash
  • bunzip
  • bzip
  • cd
  • chgrp
  • chmod
  • chown
  • clear
  • cp
  • cut
  • echo
  • expr
  • find
  • finger
  • grep
  • gunzip
  • gzip
  • head
  • hostname
  • info
  • kill
  • ln
  • ls
  • man
  • mkdir
  • more
  • mv
  • ping
  • popd
  • ps
  • pushd
  • rm
  • rmdir
  • rpm
  • set
  • stty
  • su
  • sudo
  • tail
  • tar
  • test []
  • traceroute
  • uname
  • wait
  • wc
  • where
  • who am i
  • whoami

Commonly Used Commands

Written by Maja Perušić.

Basename

Syntax

basename string [suffix]

Description

basename deletes any prefix ending in / and the suffix from string, and prints the result on the standard output. It is normally used inside substitution marks (``) within shell procedures. parameters: string- path, slash is used as directory separator character suffix- If the filename ends in suffix, it will be deleted

Example

basename somewhere/myfile.txt .txt - Takes the basename of myfile.txt which is somewhere and erases the .txt portion and then just displays myfile.


Cut

Syntax

cut [-b] [-c] [-f] list [-n] [-d delim] [-s] [file]

Description

Cuts out selected fields of each line of a file. Cut is a UNIX equivalent to the relational algebra selection operation.  If the capabilities of cut are not enough, then the alternatives are AWK and Perl.

-b list specifies byte positions (for instance, -b1-23 would pass the first 23 bytes of each line). When -b and -n are used together, list is adjusted so that no multi-byte character is split. If -b is used, the input line should contain 1023 bytes or less. -c list specifies character positions (for instance, -c1-23 would pass the first 23 characters of each line). -f list a list of fields assumed to be separated in the file by a delimiter character (see -d ); for instance, -f1,7 copies the first and seventh field only. Lines with no field delimiters will be passed through intact, unless -s is specified. If -f is used, the input line should contain 1023 characters or less. list A comma-separated or blank-character-separated list of integer field numbers (in increasing order), with optional - to indicate ranges (for instance, 1,4,7; 1-3,8; -5,10 (short for 1-5,10); or 3- (short for third through last field)). -n Doesn't split characters. -d delim The character following -d is the field delimiter (-f option only). Default is tab. Space or other characters with special meaning to the shell must be quoted. delim can be a multi-byte character. -s Suppresses lines with no delimiter characters in case of -f option. file A path name of an input file. If no file operands are specified, or if a file operand is -, the standard input will be used.


Cut can work in two modes: -- column delimited selection (each column starts with certain fixed offset defined as range from-to)

-- separator-delimited selection (with column separator being  a single character like blank, comma, colon, etc).  In this mode cut uses a delimiter defined by -d option (as in example). By default cut uses the value of delimiter stored in a shell variable called IFS (Input Field Separators) -- typically TAB.

Example

The most typical usage is cutting one of several columns from a file to create a new file.  For example: cut -d ' ' -f 2-7 retrieves the second to seventh field assuming that each field is separated by a single blank. Option -d specified a single character delimiter (in the example blank) which serves as field separator. option -f  which specifies range of fields included in the output (two to seven ).   Note that option -d presuppose usage of option -f. Column selection mode cut -c 1-5 a.dat | more  # print the first 5 characters of every line in the file a.dat Field selection mode cut -d ":" -f1,7 /etc/passwd # cuts fields 1 and 7 from /etc/passwd

Limitations

Cut is good only for simple cases. In complex cases AWK and Perl actually save your time. Limitations are many. Among them: Delimiter are single characters; they are not regular expressions. Multiple blanks are counted as multiple filed separators. Syntax is irregular and sometimes tricky. For example one character delimiters can be quoted but escaped delimiters cannot. Semantic is the most basic. Cut is essentially a text parser and as such is suitable mainly for parsing colon delimited and similar files. Functionality does even match the level of Fortran IV format statement.


Find

Syntax

Find [pathname] [-type] [-exec] [-name][-o][-a] where to search (pathname) what type of file to search for (-type: directories, data files, links) how to process the files (-exec: run a process against a selected file) the name of the file(s) (-name) perform logical operations on selections (-o and -a)

Description

an utility for searching files using the directory information, a bit similar to ls, but more effective. There are several versions of find with the main two being POSIX find used in Solaris, AIX, etc and GNU find used in linux. GNU find can be installed on Solaris and AIX and it is actually a strong recommendation as there are some differences; moreover gnu find have additional capabilities that are often useful. The popularity of find is related to the fact that it can do more then a simple tree traversal available with option -r (or -R) in many Unix utilities. Traversal provided by find can have excluded directory tree branches, can select files or directories using regular expressions, can be limited to specific types of filesystem, etc.

Examples

Find everything in your home directory modified in the last 24 hours: $ find $HOME -mtime -1 Find everything in your home directory not modified in the last seven 24-hour periods (days): $ find $HOME -mtime +7 Find any file beginning with file in the current directory and any subdirectory. $ find -name 'file*' Find any file that is larger then 1000k $ find -name '*' -size +1000k

Finger

Syntax

finger [-b] [-f] [-h] [-i] [-l] [-m] [-p] [-q] [-s] [-w] [username]

Description

A command you can use to find information about computer users. It lists the login name, full name, and other details (if there are any) about the user you are fingering. These details may include the office location and phone number, login time, idle time, time mail was last read, and the user's plan and project files. The information listed varies, and you may not be able to get any information from some sites.

-b Suppress printing the user's home directory and shell in a long format printout. -f Suppress printing the header that is normally printed in a non-long format printout. -h Suppress printing of the .project file in a long format printout. -i Force "idle" output format, which is similar to short format except that only the login name, terminal, login time, and idle time are printed. -l Force long output format. -m Match arguments only on user name (not first or last name). -p Suppress printing of the .plan file in a long format printout. -q Force quick output format, which is similar to short format except that only the login name, terminal, and login time are printed. -s Force short output format. -w Suppress printing the full name in a short format printout.

Examples

$ finger someone@random.com

This will display finger information about everyone with “someone” in their name on random.com.

The other way to use finger, to find out everyone that is currently logged on to a system, is by leaving off the username. If you are logged onto that machine already, you can just say "finger" without even the machine name, e.g.

finger someone

Locate

Syntax

locate [-d path | --database=path] [-e | --existing] [-i | --ignore-case ] [--version] [--help] pattern...

Description

List files in databases that match a pattern.

-d path --database=path Instead of searching the default file name database, search the file name databases in path, which is a colon-separated list of database file names. You can also use the environment variable LOCATE_PATH to set the list of database files to search. The option overrides the environment variable if both are used. -e --existing Only print out such names that currently exist (instead of such names that existed when the database was created). Note that this may slow down the program a lot, if there are many matches in the database. -i --ignore-case Ignore case distinctions in both the pattern and the file names. --help Print a summary of the options to locate and exit. --version Print the version number of locate and exit.

Example

$ locate perl In the above example the system would locate perl on the local machine.


Ping

Syntax

ping -s [-d] [-l] [-L] [-n] [-r] [-R] [-v] [ -i interface_address ] [-I interval] [-t ttl] host [packetsize] [count] ping [-q] [-v] [-R] [-c Count] [-i Wait] [-s PacketSize] Host

Description

The Internet Ping command bounces a small packet off a domain or IP address to test network communications, and then tells how long the packet took to make the round trip. The Ping command is one of the most commonly used utilities on the Internet by both people and automated programs for doing the most basic network test: can your computer reach another computer on the network, and if so how long does it take?

***WE SHOULD CONVER THIS TO A TABLE.***

Option Example Definition ping -c count ping -c 10 Specify the number of echo requests to send. Ping -d ping -d Set the SO_DEBUG option. Ping -f ping -f Flood ping. Sends another echo request immediately after receiving a reply to the last one. Only the super-user can use this option. Ping host ping 121.4.3.2 Specify the host name (or IP address) of computer to ping ping -i wait ping -i 2 Wait time. The number of seconds to wait between each ping ping -l preload ping -l 4 Sends "preload" packets one after another. Ping -n ping -n Numeric output, without host to symbolic name lookup. Ping -p pattern ping -p ff00 Ping Pattern. The example sends two bytes, one filled with ones, and one with zeros. Ping -q ping -q Quiet output. Only summary lines at startup and completion ping -r ping -r Direct Ping. Send to a host directly, without using routing tables. Returns an error if the host is not on a directly attached network. Ping -R Ping -R Record Route. Turns on route recording for the Echo Request packets, and display the route buffer on returned packets (ignored by many routers). ping -s PacketSize ping -s 10 Sets the packet size in number of bytes, which will result in a total packet size of PacketSize plus 8 extra bytes for the ICMP header ping -v ping -v Verbose Output. Lists individual ICMP packets, as well as Echo Responses

Examples

$ ping something.com would ping the host something.com to see if it is alive.

Su

Syntax

su [ - ] [ username [ arg ] ]

username The name of another username that you wish to log in as. arg Additional arguments that need to be passed through the su command.

Description

su (short for substitute user) is a Unix command used to run the shell of another user without logging out. It is commonly used to change to root user permissions for administrative work without logging off and back on; it is also used to switch to other users in the same way.

Example

me@localhost:~$ su Password: root@localhost:/home/me# exit logout me@localhost:~$ Additionally, one can switch to another user who is not the superuser: me@localhost:~$ su notme Password: notme@localhost:/home/me$ exit logout me@localhost:~$

Sudo =

Syntax

sudo -K | -L | -V | -h | -k | -l | -v

Description

Sudo (superuser do) allows a user with proper permissions to execute a command as the superuser or other user.

-H The -H (HOME) option sets the HOME environment variable to the homedir of the target user (root by default). By default, sudo does not modify HOME (see set_home and always_set_home in sudoers). -K The -K (sure kill) option is like -k except that it removes the user's timestamp entirely. Like -k, this option does not require a password. -L The -L (list defaults) option will list out the parameters that may be set in a Defaults line along with a short description for each. This option is useful in conjunction with grep. -V The -V (version) option causes sudo to print the version number and exit. If the invoking user is already root the -V option will print out a list of the defaults sudo was compiled with as well as the machine's local network addresses. -e The -e (edit) option indicates that, instead of running a command, the user wishes to edit one or more files. In lieu of a command, the string "sudoedit" is used when consulting the sudoers file. If the user is authorized by sudoers the following steps are taken: 1. Temporary copies are made of the files to be edited with the owner set to the invoking user. 2. The editor specified by the VISUAL or EDITOR environment variables is run to edit the temporary files. If neither VISUAL nor EDITOR are set, the program listed in the editor sudoers variable is used. 3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed. -h The -h (help) option causes sudo to print a usage message and exit. -k The -k (kill) option to sudo invalidates the user's timestamp by setting the time on it to the epoch. The next time sudo is run a password will be required. This option does not require a password and was added to allow a user to revoke sudo permissions from a .logout file. -l The -l (list) option will list out the allowed (and forbidden) commands for the user on the current host. -u The -u (user) option causes sudo to run the specified command as a user other than root. To specify a uid instead of a username, use #uid. Note that if the targetpw Defaults option is set (see sudoers) it is not possible to run commands with a uid not listed in the password database. -v If given the -v (validate) option, sudo will update the user's timestamp, prompting for the user's password if necessary. This extends the sudo timeout for another 5 minutes (or whatever the timeout is set to in sudoers) but does not run a command

Traceroute

Syntax

traceroute [-d] [-F] [-I] [-n] [-v] [-x] [-f first_ttl] [-g gateway [-g gateway] | -r] [-i iface] [-m max_ttl] [-p port] [-q nqueries] [-s src_addr] [-t tos] [-w waittime ] host [packetlen]

Description

Print the route packets take to network host.

-d Set the SO_DEBUG socket option. -F Set the "don't fragment" bit. -I Use ICMP ECHO instead of UDP datagrams. -n Print hop addresses numerically rather than symbolically and numerically. This saves a nameserver address-to-name lookup for each gateway found on the path. -v Verbose output. For each hop, the size and the destination of the response packets is displayed. Also ICMP packets received other than TIME_EXCEEDED and UNREACHABLE are listed as well. -x Prevent traceroute from calculating checksums. Note that checksums are usually required for the last hop when using ICMP ECHO probes. See the -I option. -f first_ttl Set the starting ttl value to first_ttl, to override the default value 1. traceroute skips processing for those intermediate gateways which are less than first_ttl hops away. -g gateway Specify a loose source route gateway. The user can specify more than one gateway by using -g for each gateway. The maximum that can be set is 8. -r Bypass the normal routing tables and send directly to a host on an attached network. If the host is not on a directly-attached network, an error is returned. This option can be used to send probes to a local host through an interface that has been dropped by the router daemon. -i iface Specify a network interface to obtain the source IP address for outgoing probe packets. This is normally only useful on a multi-homed host. The -s option is also another way to do this. Note that this option does not provide a way to specify the interface on which the probe packets are sent. -m max_ttl Set the maximum ttl used in outgoing probe packets. The default is 30 hops, which is the same default used for TCP connections. -p port Set the base UDP port number used in probes. The default is 33434. traceroute hopes that nothing is listening on UDP ports (base+(nhops- 1)*nqueries) to (base+(nhops*nqueries)-1)at the destination host, so that an ICMP PORT_UNREACHABLE message will be returned to terminate the route tracing. If something is listening on a port in the default range, this option can be used to select an unused port range.nhops is defined as the number of hops between the source and the destination. -q nqueries Set the desired number of probe queries. The default is 3. -s src_addr Use the following address, which usually is given as an IP address, not a hostname, as the source address in outgoing probe packets. On multi-homed hosts, those with more than one IP address, this option can be used to force the source address to be something other than the IP address traceroute picks by default. If the IP address is not one of this machine's interface addresses, an error is returned and nothing is sent. When used together with the -i option, the given IP address should be configured on the specified interface. Otherwise, an error will be returned. -t tos Set the tos(type-of-service) in probe packets to the specified value. The default is zero. The value must be an integer in the range from 0 to 255. Gateways along the path may route the probe  packet differently depending upon the tos value set in the probe packet. -w waittime Set the time, in seconds, to wait for a response to a probe. The default is five (5) seconds. host The network host.


Examples

traceroute computerhope.com - would display results similar to the following: traceroute to computerhope.com (166.70.10.23), 30 hops max, 40 byte packets 1 198.60.22.1 (198.60.22.1) 2.303 ms 1.424 ms 2.346 ms 2 krunk3.xmission.com (198.60.22.6) 0.742 ms * 1.521 ms


Uname

Syntax

uname [-a] [-i] [-m] [-n] [-p] [-r] [-s] [-v] [-X] [-S systemname]

Description

uname (unix name) is a software program in Unix and Unix-like computer operating systems. It prints the name, version and other details about the current machine and the operating system running on it. DOS, OS/2 and Microsoft Windows use ver command for that purposes.


-a Print basic information currently available from the system. -i Print the name of the hardware implementation (platform). -m Print the machine hardware name (class). Use of this option is discouraged; use uname -p instead. -n Print the nodename (the nodename is the name by which the system is known to a communications network). -p Print the current host's ISA or processor type. -r Print the operating system release level. -s Print the name of the operating system. This is the default. -v Print the operating system version. -X Print expanded system information, one information element per line, as expected by SCO Unix. The displayed information includes:

  • system name, node, release, version, machine, and number of CPUs.
  • BusType, Serial, and Users (set to "unknown" in Solaris)
  • OEM# and Origin# (set to 0 and 1, respectively)

-S systemname The nodename may be changed by specifying a system name argument. The system name argument is restricted to SYS_NMLN characters. SYS_NMLN is an implementation specific value defined in <sys/utsname.h>. Only the super-user is allowed this capability.

Examples

uname -a List the basic system information, OS release, and OS version as shown below. Linux florida 2.6.32-trunk-686 #1 SMP Thu Dec 17 00:26:04 UTC 2009 i686 GNU/Linux uname -p Display the Linux platform.

Whatis

Description

whatis searches a set of database files containing short descriptions of system commands for keywords and displays the result on the standard output. Only complete word matches are displayed. The whatis database is created using the command makewhatis.

Example

$ whatis whatis whatis(1) - search the whatis database for complete words

Whereis

Syntax

whereis [ -bmsu ] [ -BMS directory... -f ] filename ...

Description

Locate a binary, source, and manual page files for a command.

-b Search only for binaries. -m Search only for manual sections. -s Search only for sources. -u Search for unusual entries. A file is said to be unusual if it does not have one entry of each requested type. Thus `whereis -m -u *' asks for those files in the current directory which have no documentation. -B Change or otherwise limit the places where whereis searches for binaries. -M Change or otherwise limit the places where whereis searches for manual sections. -S Change or otherwise limit the places where whereis searches for sources. -f Terminate the last directory list and signals the start of file names, and must be used when any of the -B, -M, or -S options are used.

Examples

whereis -u -M /usr/man/man1 -S /usr/src -f * In the above example the whereis command would search for any manual for any file in the current directory. whereis perl Locate the directories for where Perl is stored.

Who

Syntax

who [-a] [-b] [-d] [-H] [-l] [-m] [-nx] [-p] [-q] [-r] [-s] [-t] [-T] [-u] [am i] [ file ]

Description

Displays who is on the system.

-a Process /var/adm/utmp or the named file with -b, -d, -l, -p, -r, -t, -T, and -u options turned on. -b Indicate the time and date of the last reboot. -d Display all processes that have expired and not been respawned by init . The exit field appears for dead processes and contains the termination and exit values (as returned by wait ), of the dead process. This can be useful in determining why a process terminated. -H Output column headings above the regular output. -l List only those lines on which the system is waiting for someone to login. The name field is LOGIN in such cases. Other fields are the same as for user entries except that the state field does not exist. -m Output only information about the current terminal. -n x Take a numeric argument, x, which specifies the number of users to display per line. x must be at least 1. The -n option may only be used with -q. -p List any other process which is currently active and has been previously spawned by init . The name field is the name of the program executed by init as found in /sbin/inittab. The state, line , and idle fields have no meaning. The comment field shows the id field of the line from /sbin/inittab that spawned this process. -q (quick who ) display only the names and the number of users currently logged on. When this option is used, all other options are ignored. -r Indicate the current run-level of the init process. -s (default) List only the name, line, and time fields. -t Indicate the last change to the system clock (using the date utility) by root. See su and date . -T Same as the -s option, except that the state field is also written. state is one of the characters listed under the /usr/bin/who version of this option. If the -u option is used with -T, the idle time is added to the end of the previous format. -u List only those users who are currently logged in. file Specify a path name of a file to substitute for the database of logged-on users that who uses by default.

Example

Who -b system boot 2009-12-22 07:57


Whoami

Whoami is a command found on most Unix-like operating systems, Windows Vista and Windows Server 2008. It prints userid (username) of the current user when invoked. It has the same effect as the Unix command id -un. On Unix-like operating systems, the output of the command is slightly different from $USER because whoami outputs the username that the user is working under, whereas $USER outputs the username that was used to login. For example, if the user logged in as John and su into root, whoami displays root and echo $USER displays John. This is because the su command does not invoke a login shell by default.


Xargs

Syntax

xargs [options] [command]

Description

The xargs command creates an argument list for command from standard input. It is typically used with a pipe getting its input from commands like ls and find  The latter is probably the most common source of xargs input and is covered in example. If no command is specified, xargs works similar to the echo command and prints the argument list to standard output.

Options

-n# Execute command once for every # argument. For example, -n2 bundles arguments into groups of two or less and executes command on each argument bundle.  -l# Execute command once for every # lines of input. For example, -l1 creates a bundle of arguments for every one line of input and executes command on each argument bundle. -i Normally xargs places input arguments at the end of command. Used with the -i option, xargs will replace all instances of {} with input arguments. You need to put them in single brackets or use a backslash (\) before each bracket to keep the shell from interpreting the special characters. -t Echo each command before executing. Nice for debugging -p Prompts the user before executing each command.  Useful for debugging.

Examples

find . -type f -mtime -1 -print | xargs pr –n Find any files that have a modified time of 1 day and print the contents of each of those files.

find Members/ -type f -print0 | xargs -0 grep "examplestring" In the above example the find command finds all files in the Members directory each file that is found is then searched using grep for the text "examplestring".