Wrap around mode что обозначает в xterm
Перейти к содержимому

Wrap around mode что обозначает в xterm

  • автор:

Running containers

Docker runs processes in isolated containers. A container is a process which runs on a host. The host may be local or remote. When you execute docker run , the container process that runs is isolated in that it has its own file system, its own networking, and its own isolated process tree separate from the host.

This page details how to use the docker run command to run containers.

General form

A docker run command takes the following form:

The docker run command must specify an image reference to create the container from.

Image references

The image reference is the name and version of the image. You can use the image reference to create or run a container based on an image.

  • docker run IMAGE[:TAG][@DIGEST]
  • docker create IMAGE[:TAG][@DIGEST]

An image tag is the image version, which defaults to latest when omitted. Use the tag to run a container from specific version of an image. For example, to run version 23.10 of the ubuntu image: docker run ubuntu:23.10 .

Image digests

Images using the v2 or later image format have a content-addressable identifier called a digest. As long as the input used to generate the image is unchanged, the digest value is predictable.

The following example runs a container from the alpine image with the sha256:9cacb71397b640eca97488cf08582ae4e4068513101088e9f96c9814bfda95e0 digest:

Options

[OPTIONS] let you configure options for the container. For example, you can give the container a name ( —name ), or run it as a background process ( -d ). You can also set options to control things like resource constraints and networking.

Commands and arguments

You can use the [COMMAND] and [ARG. ] positional arguments to specify commands and arguments for the container to run when it starts up. For example, you can specify sh as the [COMMAND] , combined with the -i and -t flags, to start an interactive shell in the container (if the image you select has an sh executable on PATH ).

Note

Depending on your Docker system configuration, you may be required to preface the docker run command with sudo . To avoid having to use sudo with the docker command, your system administrator can create a Unix group called docker and add users to it. For more information about this configuration, refer to the Docker installation documentation for your operating system.

Foreground and background

When you start a container, the container runs in the foreground by default. If you want to run the container in the background instead, you can use the —detach (or -d ) flag. This starts the container without occupying your terminal window.

While the container runs in the background, you can interact with the container using other CLI commands. For example, docker logs lets you view the logs for the container, and docker attach brings it to the foreground.

            For more information about docker run flags related to foreground and background modes, see:
  • docker run —detach : run container in background
  • docker run —attach : attach to stdin , stdout , and stderr
  • docker run —tty : allocate a pseudo-tty
  • docker run —interactive : keep stdin open even if not attached

For more information about re-attaching to a background container, see docker attach

Container identification

You can identify a container in three ways:

Identifier type Example value
UUID long identifier f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778
UUID short identifier f78375b1c487
Name evil_ptolemy

The UUID identifier is a random ID assigned to the container by the daemon.

The daemon generates a random string name for containers automatically. You can also defined a custom name using the —name flag

. Defining a name can be a handy way to add meaning to a container. If you specify a name , you can use it when referring to the container in a user-defined network. This works for both background and foreground Docker containers.

A container identifier is not the same thing as an image reference. The image reference specifies which image to use when you run a container. You can’t run docker exec nginx:alpine sh to open a shell in a container based on the nginx:alpine image, because docker exec expects a container identifier (name or ID), not an image.

While the image used by a container is not an identifier for the container, you find out the IDs of containers using an image by using the —filter flag. For example, the following docker ps command gets the IDs of all running containers based on the nginx:alpine image:

For more information about using filters, see Filtering

Container networking

Containers have networking enabled by default, and they can make outgoing connections. If you’re running multiple containers that need to communicate with each other, you can create a custom network and attach the containers to the network.

When multiple containers are attached to the same custom network, they can communicate with each other using the container names as a DNS hostname. The following example creates a custom network named my-net , and runs two containers that attach to the network.

For more information about container networking, see Networking overview

Filesystem mounts

By default, the data in a container is stored in an ephemeral, writable container layer. Removing the container also removes its data. If you want to use persistent data with containers, you can use filesystem mounts to store the data persistently on the host system. Filesystem mounts can also let you share data between containers and the host.

Docker supports two main categories of mounts:

  • Volume mounts
  • Bind mounts

Volume mounts are great for persistently storing data for containers, and for sharing data between containers. Bind mounts, on the other hand, are for sharing data between a container and the host.

You can add a filesystem mount to a container using the —mount flag for the docker run command.

The following sections show basic examples of how to create volumes and bind mounts. For more in-depth examples and descriptions, refer to the section of the storage section

in the documentation.

Volume mounts

To create a volume mount:

The --mount flag takes two parameters in this case: source and target . The value for the source parameter is the name of the volume. The value of target is the mount location of the volume inside the container. Once you've created the volume, any data you write to the volume is persisted, even if you stop or remove the container:
 /foo/hello.txt    

The target must always be an absolute path, such as /src/docs . An absolute path starts with a / (forward slash). Volume names must start with an alphanumeric character, followed by a-z0-9 , _ (underscore), . (period) or — (hyphen).

Bind mounts

To create a bind mount:

In this case, the —mount flag takes three parameters. A type ( bind ), and two paths. The source path is a the location on the host that you want to bind mount into the container. The target path is the mount destination inside the container.

Bind mounts are read-write by default, meaning that you can both read and write files to and from the mounted location from the container. Changes that you make, such as adding or editing files, are reflected on the host filesystem:

  /foo/hello.txt    

Exit status

The exit code from docker run gives information about why the container failed to run or why it exited. The following sections describe the meanings of different container exit codes values.

125

Exit code 125 indicates that the error is with Docker daemon itself.

  Exit code 126 indicates that the specified contained command can't be invoked. The container command in the following example is: /etc; echo $? .
 Exit code 127 indicates that the contained command can't be found.

Any exit code other than 125 , 126 , and 127 represent the exit code of the provided container command.

The operator can also adjust the performance parameters of the container:

Option Description
-m , —memory=»» Memory limit (format: [] ). Number is a positive integer. Unit can be one of b , k , m , or g . Minimum is 6M.
—memory-swap=»» Total memory limit (memory + swap, format: [] ). Number is a positive integer. Unit can be one of b , k , m , or g .
—memory-reservation=»» Memory soft limit (format: [] ). Number is a positive integer. Unit can be one of b , k , m , or g .
—kernel-memory=»» Kernel memory limit (format: [] ). Number is a positive integer. Unit can be one of b , k , m , or g . Minimum is 4M.
-c , —cpu-shares=0 CPU shares (relative weight)
—cpus=0.000 Number of CPUs. Number is a fractional number. 0.000 means no limit.
—cpu-period=0 Limit the CPU CFS (Completely Fair Scheduler) period
—cpuset-cpus=»» CPUs in which to allow execution (0-3, 0,1)
—cpuset-mems=»» Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems.
—cpu-quota=0 Limit the CPU CFS (Completely Fair Scheduler) quota
—cpu-rt-period=0 Limit the CPU real-time period. In microseconds. Requires parent cgroups be set and cannot be higher than parent. Also check rtprio ulimits.
—cpu-rt-runtime=0 Limit the CPU real-time runtime. In microseconds. Requires parent cgroups be set and cannot be higher than parent. Also check rtprio ulimits.
—blkio-weight=0 Block IO weight (relative weight) accepts a weight value between 10 and 1000.
—blkio-weight-device=»» Block IO weight (relative device weight, format: DEVICE_NAME:WEIGHT )
—device-read-bps=»» Limit read rate from a device (format: :[] ). Number is a positive integer. Unit can be one of kb , mb , or gb .
—device-write-bps=»» Limit write rate to a device (format: :[] ). Number is a positive integer. Unit can be one of kb , mb , or gb .
—device-read-iops=»» Limit read rate (IO per second) from a device (format: : ). Number is a positive integer.
—device-write-iops=»» Limit write rate (IO per second) to a device (format: : ). Number is a positive integer.
—oom-kill-disable=false Whether to disable OOM Killer for the container or not.
—oom-score-adj=0 Tune container’s OOM preferences (-1000 to 1000)
—memory-swappiness=»» Tune a container’s memory swappiness behavior. Accepts an integer between 0 and 100.
—shm-size=»» Size of /dev/shm . The format is . number must be greater than 0 . Unit is optional and can be b (bytes), k (kilobytes), m (megabytes), or g (gigabytes). If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses 64m .

User memory constraints

We have four ways to set user memory usage:

Option Result
memory=inf, memory-swap=inf (default) There is no memory limit for the container. The container can use as much memory as needed.
memory=L (specify memory and set memory-swap as -1 ) The container is not allowed to use more than L bytes of memory, but can use as much swap as is needed (if the host supports swap memory).
memory=L (specify memory without memory-swap) The container is not allowed to use more than L bytes of memory, swap plus memory usage is double of that.
memory=L (specify both memory and memory-swap) The container is not allowed to use more than L bytes of memory, swap plus memory usage is limited by S.

We set nothing about memory, this means the processes in the container can use as much memory and swap memory as they need.

We set memory limit and disabled swap memory limit, this means the processes in the container can use 300M memory and as much swap memory as they need (if the host supports swap memory).

We set memory limit only, this means the processes in the container can use 300M memory and 300M swap memory, by default, the total virtual memory size (—memory-swap) will be set as double of memory, in this case, memory + swap would be 2*300M, so processes can use 300M swap memory as well.

We set both memory and swap memory, so the processes in the container can use 300M memory and 700M swap memory.

Memory reservation is a kind of memory soft limit that allows for greater sharing of memory. Under normal circumstances, containers can use as much of the memory as needed and are constrained only by the hard limits set with the -m / —memory option. When memory reservation is set, Docker detects memory contention or low memory and forces containers to restrict their consumption to a reservation limit.

Always set the memory reservation value below the hard limit, otherwise the hard limit takes precedence. A reservation of 0 is the same as setting no reservation. By default (without reservation set), memory reservation is the same as the hard memory limit.

Memory reservation is a soft-limit feature and does not guarantee the limit won’t be exceeded. Instead, the feature attempts to ensure that, when memory is heavily contended for, memory is allocated based on the reservation hints/setup.

The following example limits the memory ( -m ) to 500M and sets the memory reservation to 200M.

Under this configuration, when the container consumes memory more than 200M and less than 500M, the next system memory reclaim attempts to shrink container memory below 200M.

The following example set memory reservation to 1G without a hard memory limit.

The container can use as much memory as it needs. The memory reservation setting ensures the container doesn’t consume too much memory for long time, because every memory reclaim shrinks the container’s consumption to the reservation.

By default, kernel kills processes in a container if an out-of-memory (OOM) error occurs. To change this behaviour, use the —oom-kill-disable option. Only disable the OOM killer on containers where you have also set the -m/—memory option. If the -m flag is not set, this can result in the host running out of memory and require killing the host’s system processes to free memory.

The following example limits the memory to 100M and disables the OOM killer for this container:

The following example, illustrates a dangerous way to use the flag:

The container has unlimited memory which can cause the host to run out memory and require killing system processes to free memory. The —oom-score-adj parameter can be changed to select the priority of which containers will be killed when the system is out of memory, with negative scores making them less likely to be killed, and positive scores more likely.

Kernel memory constraints

Kernel memory is fundamentally different than user memory as kernel memory can’t be swapped out. The inability to swap makes it possible for the container to block system services by consuming too much kernel memory. Kernel memory includes:

  • stack pages
  • slab pages
  • sockets memory pressure
  • tcp memory pressure

You can setup kernel memory limit to constrain these kinds of memory. For example, every process consumes some stack pages. By limiting kernel memory, you can prevent new processes from being created when the kernel memory usage is too high.

Kernel memory is never completely independent of user memory. Instead, you limit kernel memory in the context of the user memory limit. Assume «U» is the user memory limit and «K» the kernel limit. There are three possible ways to set limits:

Option Result
U != 0, K = inf (default) This is the standard memory limitation mechanism already present before using kernel memory. Kernel memory is completely ignored.
U != 0, K < U Kernel memory is a subset of the user memory. This setup is useful in deployments where the total amount of memory per-cgroup is overcommitted. Overcommitting kernel memory limits is definitely not recommended, since the box can still run out of non-reclaimable memory. In this case, you can configure K so that the sum of all groups is never greater than the total memory. Then, freely set U at the expense of the system’s service quality.
U != 0, K > U Since kernel memory charges are also fed to the user counter and reclamation is triggered for the container for both kinds of memory. This configuration gives the admin a unified view of memory. It is also useful for people who just want to track kernel memory usage.

We set memory and kernel memory, so the processes in the container can use 500M memory in total, in this 500M memory, it can be 50M kernel memory tops.

We set kernel memory without -m, so the processes in the container can use as much memory as they want, but they can only use 50M kernel memory.

Swappiness constraint

By default, a container’s kernel can swap out a percentage of anonymous pages. To set this percentage for a container, specify a —memory-swappiness value between 0 and 100. A value of 0 turns off anonymous page swapping. A value of 100 sets all anonymous pages as swappable. By default, if you are not using —memory-swappiness , memory swappiness value will be inherited from the parent.

For example, you can set:

Setting the —memory-swappiness option is helpful when you want to retain the container’s working set and to avoid swapping performance penalties.

CPU share constraint

By default, all containers get the same proportion of CPU cycles. This proportion can be modified by changing the container’s CPU share weighting relative to the weighting of all other running containers.

To modify the proportion from the default of 1024, use the -c or —cpu-shares flag to set the weighting to 2 or higher. If 0 is set, the system will ignore the value and use the default of 1024.

The proportion will only apply when CPU-intensive processes are running. When tasks in one container are idle, other containers can use the left-over CPU time. The actual amount of CPU time will vary depending on the number of containers running on the system.

For example, consider three containers, one has a cpu-share of 1024 and two others have a cpu-share setting of 512. When processes in all three containers attempt to use 100% of CPU, the first container would receive 50% of the total CPU time. If you add a fourth container with a cpu-share of 1024, the first container only gets 33% of the CPU. The remaining containers receive 16.5%, 16.5% and 33% of the CPU.

On a multi-core system, the shares of CPU time are distributed over all CPU cores. Even if a container is limited to less than 100% of CPU time, it can use 100% of each individual CPU core.

For example, consider a system with more than three cores. If you start one container with -c=512 running one process, and another container with -c=1024 running two processes, this can result in the following division of CPU shares:

PID container CPU CPU share 100 0 100% of CPU0 101 1 100% of CPU1 102 2 100% of CPU2 

CPU period constraint

The default CPU CFS (Completely Fair Scheduler) period is 100ms. We can use —cpu-period to set the period of CPUs to limit the container’s CPU usage. And usually —cpu-period should work with —cpu-quota .

If there is 1 CPU, this means the container can get 50% CPU worth of run-time every 50ms.

In addition to use —cpu-period and —cpu-quota for setting CPU period constraints, it is possible to specify —cpus with a float number to achieve the same purpose. For example, if there is 1 CPU, then —cpus=0.5 will achieve the same result as setting —cpu-period=50000 and —cpu-quota=25000 (50% CPU).

The default value for —cpus is 0.000 , which means there is no limit.

Cpuset constraint

We can set cpus in which to allow execution for containers.

Saved searches

Use saved searches to filter your results more quickly

Cancel Create saved search

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

xtermjs / xterm.js Public

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support reverse-wraparound mode? #2716

backspace opened this issue Feb 12, 2020 · 12 comments · Fixed by #2724

Support reverse-wraparound mode? #2716

backspace opened this issue Feb 12, 2020 · 12 comments · Fixed by #2724
type/enhancement Features or improvements to existing features

Comments

backspace commented Feb 12, 2020 •

I’m implementing a highly-restricted terminal with Xterm.js to allow users to edit their desired remote execution command before they connect to a true terminal. The editable portion of the line is only at the end; the rest represents the full command that one would use to perform the same action in a non-web terminal.

It’s a bit hackish to be interpreting keyboard events to edit a string, but it’s been working well enough. However, I’ve now found that if the editable part of the command wraps to another line, backspacing doesn’t wrap to the previous line. I found this Super User answer that suggests I could use “reverse-wraparound mode” in a true xterm, but sending that to the Xterm.js terminal didn’t change the behaviour.

Reverse-wraparound mode is mentioned in some comments in Xterm.js’s input handler, but it seems like it’s not handled.

Is there any chance that this mode will be supported? If not I can surely detect whether backspacing has reached the beginning of the line and move to the previous one if necessary, but I thought I’d ask in case there’s hope that this will be added or if there’s something I’m missing, because handling it manually seems like it’ll add more brittleness. If there’s any desire for it to be incorporated into Xterm.js, I could try making a PR!

Thanks for all the work on this, it works perfectly once the remote session has begun, it’s impressively powerful ��

The text was updated successfully, but these errors were encountered:

Saved searches

Use saved searches to filter your results more quickly

Cancel Create saved search

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

xtermjs / xterm.js Public

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wrap issue when prompt is over 2 lines #2752

adamjimenez opened this issue Mar 9, 2020 · 27 comments

wrap issue when prompt is over 2 lines #2752

adamjimenez opened this issue Mar 9, 2020 · 27 comments

Comments

adamjimenez commented Mar 9, 2020

The cursor positioning is off when backspacing if the prompt is over two lines:

Also is there a way to remove the path from the prompt?

The text was updated successfully, but these errors were encountered:

Tyriar added the needs more info label Mar 9, 2020
adamjimenez commented Mar 9, 2020 via email
own program
— Best regards, Adam Jimenez
jerch commented Mar 9, 2020

Backspacing into previous line? This should not be possible at all until #2724 has landed and got activated by an explicit CSI command.

@adamjimenez Can you give abit more context, how you set up xterm.js?

adamjimenez commented Mar 10, 2020

I’m using xterm in ShiftEdit. The back-end is provided by ttyx.

jerch commented Mar 10, 2020 •

@adamjimenez Looking at your code in https://github.com/adamjimenez/shiftedit/blob/fb218169a4e323e78697887ecbfb70fe43ff31f1/app/ssh.js#L182 I wonder what that custom key handler is used for? Normally you dont have to deal with any key overrides yourself, xterm.js handles that for you and you can simply work with data from onData . Not sure if this code is related to the issue.

Thats way outdated, plz consider upgrading to a newer version. xterm.js is a volunteer project, thus we cannot provide LTS for old release.

Back on the issue at hand:
There must be some code that is responsible for the cursor move into the previous line. Start digging there (a wild guess — that code might wrongly account EOL chars \r\n into offset calculation). xterm.js does not support backspacing into previous lines (yet).

adamjimenez commented Mar 10, 2020

@jerch The reason for the custom key handler is to handle multiple instances so that the data is passed to the correct instance.

I’ve updated to xterm@4.0.2 and am seeing a similar pattern of behaviour when the prompt wraps onto three lines.

BTW thanks for the support, the fact that you dug into my repo to help me out speaks volumes ��

jerch commented Mar 10, 2020 •

Oh well, I overlooked that — so you only see this, if its a shell prompt over several lines? Thats an important bit of info, because shells are smarter in line processing and actually move the cursor around.

Can you switch the log level to ‘debug’ ( new Terminal() ) and post the console.log here? Also check if the pty and the terminal have the same size when this happens. Furthermore — does this only happen after resize or always (we have a known race condition in resize which tends to trigger for overlong shell prompts)?

adamjimenez commented Mar 11, 2020

Yes, it does appear to have something to do with the shell prompt.

I’ve enabled logs and captured this recording:

It happens with or without resize.

jerch commented Mar 11, 2020 •

@adamjimenez Yes, sadly that is a known race condition we cannot do much about currently as it needs a fundamental rewrite of the resize cycling and propagation between xterm.js and the pty/process. Furthermore, even with this rewrite we cannot completely avoid it, and the rewrite would introduce pretty bad delay during resizing. So its not yet clear how even a partial fix should look like.

@Tyriar Were there some recent changes regarding this? Seems we get more often issue reports now?

jerch commented Mar 11, 2020

@adamjimenez Did some further tests with other emulators and different shells. For me this faulty behavior is always reproducible with bash in any emulator (tested gnome-terminal, xterm, konsole, rxvt): as soon as the prompt content hits the third line, it goes all bonkers. No matter if there is pending input behind or not. Which actually makes me think, that it might be a bug in bashs prompt refreshing? Are you using bash by any chance? Also note that I cannot repro it with zsh. Tested on Ubuntu 18 LTS with bash v4.4.20.

adamjimenez commented Mar 12, 2020

Thanks for digging into this. Can confirm, I’m also on Ubuntu 18LTS with bash v4.4.20

jerch commented Mar 12, 2020 •

This issue reveals a zoo of quirks and broken workarounds. On both ends, xterm.js and shells.

Did some further tests with bash and zsh, all were done with a clean longish PS1 string containing only ‘a’. This is needed to avoid runwidth calc errors in libreadline, more on this below.

Results:
Currently all shells redraw their prompt on their own after a resize. For this they all rely on the old resize behavior w’o reflowing, thus they think the cursor is stable in terms of rows and would only change col offset. From this assumption they calc the needed area to be cleaned up to the beginning of the prompt, and basically redraw the whole prompt.

Problem1:
@Tyriar was aware of that problem and kinda implemented a «sticky» rule in the reflow algo, that would reflow all bufferlines, except the last ones joined by isWrapped (where the cursor is?), which would follow the old resize logic. This is error prone on its own, but works most of the time, if the cursor is indeed in a shell prompt line. Still this will break the cursor line in any non shell REPL, that does not redraw that screen part on resize. (@Tyriar plz correct me, if I put it the wrong way. )

Problem2:
zsh puts a hard linebreak (‘\r\n’) into the prompt line, if the prompt happens to end at the last cell in a row, just to get the cursor at the beginning of the next line. This is toxic for the reflow logic above, as now the sticky rule only applies to that newish row. Solution would be easy on zsh side: instead of doing a hard linebreak, put there a space + BS, which results in the same screen output, but would mark the new row as wrapped, thus count into the sticky part. Btw bash gets this one right.

Problem3:
bash wrongly calcs parts to be deleted, if the prompt filled a row to the last cell, and resize enlarges the viewport. It always misses chars at the end. Weird though, that this only happens, if the last was full. Looking at their cleanup code explains why: seems they send CR EL0 CUU(times wrap) PROMPT , but for a full line the cursor is already at the beginning of the next line, thus they miss erasing the line before, and the prompt overwrites now less cells keeping old stuff in excess cells. Since bash does not mess with hard linebreak, it works otherwise.

Btw the problem mentioned in #2752 (comment) went away with the clean PS1 string. There is something wrong with Ubuntu’s default PS1 line, bash has troubles to correctly calc the runwidth of it. I double checked with the actual printout set hard as PS1 line, which works again.

Solution?
Well, I think a clean solution would be:

  • remove the quirks for shell prompts from reflow, thus also reflow the cursor row normally
  • announce somehow, whether the terminal does static resize or reflow (env var? DA attribute?), a shell should eval that bit of information and decide, whether to redraw itself or to rely on terminal reflow

Or get the shell extension proposed by @PerBothner done, this way a shell can mark its prompt and we can skip those lines during reflowing more reliably. In any case — both solutions would require the shells to play along. Not even sure if any shell cares for reflow, xterm doesnt have it, so why bothering? 😉

Found an old conversation on the bash mailing list about this (~2016), which also mentioned @egmontkob, but it kinda ended somewhere between the lines «not our fault | cannot do much about it | not sure who to blame», which is not getting us anywhere.

Unix and Linux [4th ed] 9780321636782, 0321636783

UNIX and Linux system administration handbook [4th ed., 5th printing] 9780131480056, 0131480057, 4520100054

Table of contents :
Cover. Page 1
Table of Contents. Page 6
Introduction. Page 12
Chapter 1: Getting Started with Unix. Page 16
Accessing a Unix System. Page 18
Connecting to the Unix System. Page 22
Logging In. Page 25
Changing Your Password with passwd. Page 26
Listing Directories and Files with ls. Page 28
Changing Directories with cd. Page 30
Finding Yourself with pwd. Page 32
Piping Input and Output. Page 33
Redirecting Output. Page 34
Using Wildcards. Page 36
Viewing File Contents with more. Page 37
Displaying File Contents with cat. Page 38
Exploring the System. Page 40
Getting Help with man. Page 41
Logging Out. Page 43
Chapter 2: Using Directories and Files. Page 44
Creating Directories with mkdir. Page 45
Creating Files with touch. Page 47
Copying Directories and Files with cp. Page 49
Listing Directories and Files with ls (More Goodies). Page 51
Moving Files with mv. Page 53
Removing Files with rm. Page 54
Removing Directories with rmdir. Page 57
Finding Forgotten Files with find. Page 59
Locating Lost Files with locate. Page 61
Linking with ln (Hard Links). Page 62
Linking with ln -s (Soft Links). Page 64
Chapter 3: Working with Your Shell. Page 66
Discovering Which Shell You’re Using. Page 67
Understanding Shells and Options. Page 68
Changing Your Shell with chsh. Page 70
Changing Your Shell Temporarily. Page 72
Using Completion in the bash Shell. Page 74
Viewing Session History in the bash Shell. Page 75
Using Completion in the zsh Shell. Page 77
Viewing Session History in the zsh Shell. Page 78
Changing Your Identity with su. Page 80
Fixing Terminal Settings with stty. Page 82
Exiting the Shell. Page 83
Chapter 4: Creating and Editing Files. Page 84
Choosing an Editor. Page 85
Starting pico and Dabbling with It. Page 88
Saving in pico. Page 89
Cutting and Pasting Text Blocks in pico. Page 90
Checking Spelling in pico. Page 91
Getting Help in pico. Page 92
Exiting pico. Page 93
Starting vi and Dabbling with It. Page 94
Saving in vi. Page 96
Adding and Deleting Text in vi. Page 97
Importing Files into vi. Page 98
Searching and Replacing in vi. Page 99
Exiting vi. Page 101
Starting emacs and Dabbling with It. Page 102
Using emacs Menus to Spell-Check. Page 104
Saving in emacs. Page 105
Exiting emacs. Page 106
Chapter 5: Controlling Ownership and Permissions. Page 108
Understanding File Ownership and Permissions. Page 109
Finding Out Who Owns What. Page 110
Finding Out Which Group You’re In. Page 112
Changing the Group Association of Files and Directories with chgrp. Page 114
Changing Ownership of Files and Directories with chown. Page 116
Changing Permissions with chmod. Page 118
Translating Mnemonic Permissions to Numeric Permissions. Page 121
Changing Permission Defaults with umask. Page 122
Chapter 6: Manipulating Files. Page 124
Counting Files and Their Contents with wc. Page 125
Viewing File Beginnings with head. Page 126
Viewing File Endings with tail. Page 127
Finding Text with grep. Page 128
Using Regular Expressions with grep. Page 129
Using Other Examples of Regular Expressions. Page 131
Making Global Changes with sed. Page 132
Changing Files with awk. Page 133
Comparing Files with cmp. Page 135
Finding Differences in Files with diff. Page 136
Finding Differences in Files with sdiff. Page 137
Sorting Files with sort. Page 138
Eliminating Duplicates with uniq. Page 140
Redirecting to Multiple Locations with tee. Page 141
Changing with tr. Page 142
Formatting with fmt. Page 144
Splitting Files with split. Page 146
Chapter 7: Getting Information About the System. Page 148
Getting System Information with uname. Page 149
Viewing File Systems with df. Page 150
Determining Disk Usage with du. Page 153
Finding Out File Types with file. Page 154
Finding Out About Users with finger. Page 155
Learning Who Else Is Logged in with who. Page 158
Learning Who Else Is Logged in with w. Page 159
Getting Information About Your Userid with id. Page 161
Chapter 8: Configuring Your Unix Environment. Page 162
Understanding Your Unix Environment. Page 163
Discovering Your Current Environment. Page 165
Adding or Changing Variables. Page 167
Looking at Your zsh Configuration Files. Page 169
Adding to Your zsh Path. Page 173
Changing Your zsh Prompt. Page 175
Looking at Your bash Configuration Files. Page 178
Adding to Your bash Path. Page 181
Changing Your bash Prompt. Page 183
Setting Aliases with alias. Page 185
Chapter 9: Running Scripts and Programs. Page 188
Running a Command. Page 189
Scheduling Onetime Jobs with at. Page 190
Scheduling Regularly Occurring Jobs with cron. Page 193
Suspending Jobs. Page 195
Checking Job Status with jobs. Page 196
Running Jobs in the Background with bg. Page 197
Running Jobs in the Foreground with fg. Page 198
Controlling Job Priority with nice. Page 199
Timing Jobs with time. Page 200
Finding Out What Processes Are Running with ps. Page 202
Deleting Processes with kill. Page 204
Chapter 10: Writing Basic Scripts. Page 206
Creating a Shell Script. Page 207
Running a Shell Script. Page 209
Making a Script Executable. Page 210
Getting a Head Start on Scripts with history. Page 212
Embedding Commands. Page 213
Looping Your Scripts. Page 215
Creating If-Then Statements. Page 217
Accepting Command-Line Arguments in Your Scripts. Page 220
Accepting Input While a Script Is Running. Page 221
Debugging Scripts. Page 223
Chapter 11: Sending and Reading E-mail. Page 224
Choosing an E-mail Program and Getting Started. Page 225
Reading E-mail with pine. Page 227
Sending E-mail with pine. Page 229
Customizing pine. Page 231
Reading E-mail with mutt. Page 233
Sending E-mail with mutt. Page 235
Reading E-mail with mail. Page 237
Sending E-mail with mail. Page 238
Creating a Signature File. Page 240
Automatically Forwarding Incoming Messages. Page 242
Announcing an Absence with vacation. Page 243
Configuring procmail. Page 245
Managing E-mail with procmail. Page 247
Chapter 12: Accessing the Internet. Page 250
Getting Familiar with Unix Internet Lingo. Page 251
Logging in to Remote Systems with ssh. Page 253
Logging in to Remote Systems with telnet. Page 254
Communicating with Others Using write. Page 256
Communicating with Others Using talk. Page 257
Getting Files from the Internet with ftp. Page 258
Sharing Files on the Internet with ftp. Page 262
Surfing the Web with links. Page 264
Surfing the Web with lynx. Page 266
Downloading Web Sites with wget. Page 268
Checking Connections with ping. Page 269
Tracing Connections with traceroute. Page 270
Matching Domain Names with IP Addresses. Page 272
Chapter 13: Working with Encoded and Compressed Files. Page 274
Encoding Files with uuencode. Page 275
Decoding Files with uudecode. Page 278
Archiving with tar. Page 279
Unarchiving Files with tar. Page 281
Compressing Files with compress. Page 282
Uncompressing Files with uncompress. Page 283
Zipping a File or Directory with gzip. Page 284
Unzipping a gzip File with gunzip. Page 285
Zipping Files and Directories with zip. Page 286
Unzipping Zipped Files with unzip. Page 287
Combining Commands. Page 288
Chapter 14: Using Handy Utilities. Page 290
Calendaring with cal. Page 291
Calculating with bc. Page 294
Evaluating Expressions with expr. Page 295
Converting with units. Page 296
Looking It Up with look. Page 297
Keeping a Record of Your Session with script. Page 298
Chapter 15: Being Root. Page 302
Acting Like root with sudo. Page 303
Becoming root with su. Page 305
Starting, Stopping, and Restarting Daemons. Page 307
Changing the System Configuration. Page 309
Monitoring the System. Page 311
Keeping up with watch. Page 314
Checking Boot Messages with dmesg. Page 315
Setting the Date and Time. Page 317
Chapter 16: Sensational Unix Tricks. Page 318
Cleaning Up HTML Documents with tidy. Page 319
Searching and Replacing Throughout Multiple Documents with sed. Page 322
Generating Reports with awk. Page 325
Using Input to Customize Your Environment. Page 326
Using ROT13 Encoding with sed. Page 328
Embedding ROT13 Encoding in a Shell Script. Page 330
Making Backups with rsync. Page 333
Using Advanced Redirection with stderr. Page 335
Appendix A: Unix Reference. Page 338
Appendix B: What’s What and What’s Where. Page 354
Appendix C: Commands and Flags. Page 358
A. Page 392
C. Page 393
E. Page 395
F. Page 397
G. Page 398
I. Page 399
L. Page 400
O. Page 401
P. Page 402
R. Page 403
S. Page 404
T. Page 406
V. Page 407
Z. Page 408

Citation preview

VISUAL QUICKstart GUIDE

unix and linux Fourth Edition

Deborah S. Ray and Eric J. Ray

Visual QuickStart Guide

Unix and Linux, Fourth Edition Deborah S. Ray and Eric J. Ray

Peachpit Press 1249 Eighth Street Berkeley, CA 94710 510/524-2178 510/524-2221 ( fax) Find us on the Web at: www.peachpit.com To report errors, please send a note to: [email protected] Peachpit Press is a division of Pearson Education. Copyright © 2009 by Deborah Ray and Eric Ray Editor: Rebecca Gulick Copy Editor: Liz Welch Proofreader: Elle Yoko Suzuki Production Coordinator: Myrna Vladic Compositor: Debbie Roberti Technical Reviewer: Stephen Talley Indexer: James Minkin Cover design: Peachpit Press

Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected].

Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the authors nor Peachpit Press shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it.

Trademarks Visual QuickStart Guide is a registered trademark of Peachpit Press, a division of Pearson Education. Other product names used in this book may be trademarks of their own respective owners. Images of Web sites in this book are copyrighted by the original holders and are used with their kind permission. This book is not officially endorsed by nor affiliated with any of the above companies. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. ISBN 13: 978-0-321-63678-2 ISBN 10: 0-321-63678-3 987654321 Printed and bound in the United States of America

Dedication To each other, Ashleigh, and Alex.

Acknowledgments This book came together with the invaluable assistance of a number of very talented and supportive people. Thanks to Clifford Colby for his continued confidence and support. Rebecca Gulick was a delight to work with and helped tremendously in pulling the various pieces together. Elle Yoko Suzuki was not only great as a proofreader, but provided super technical feedback as well. Liz Welch was really helpful as copy editor. Myrna Vladic and Deb Roberti did a great job in production, even with our special needs. And, yet again, Steve Talley’s careful attention to detail and deep knowledge of the idiosyncrasies of Unix helped iron out technical rough spots. Thanks, all!

Table of Contents Introduction Chapter 1: Getting Started with Unix

Chapter 2: Using Directories and Files

Creating Directories with mkdir. . . . . . . . . . . . . . . . . . 30 Creating Files with touch . . . . . . . . . . . . . . . . . . . . . . . . 32 Copying Directories and Files with cp . . . . . . . . . . . . 34 Listing Directories and Files with ls (More Goodies) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 Moving Files with mv. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 Removing Files with rm . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Removing Directories with rmdir . . . . . . . . . . . . . . . . 42 Finding Forgotten Files with find. . . . . . . . . . . . . . . . 44 Locating Lost Files with locate. . . . . . . . . . . . . . . . . . 46 Linking with ln (Hard Links). . . . . . . . . . . . . . . . . . . . . 47 Linking with ln -s (Soft Links) . . . . . . . . . . . . . . . . . . 49

Table of Contents

Accessing a Unix System. . . . . . . . . . . . . . . . . . . . . . . . . . 3 Connecting to the Unix System . . . . . . . . . . . . . . . . . . . 7 Logging In. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Changing Your Password with passwd. . . . . . . . . . . . 11 Listing Directories and Files with ls. . . . . . . . . . . . . . 13 Changing Directories with cd . . . . . . . . . . . . . . . . . . . . 15 Finding Yourself with pwd . . . . . . . . . . . . . . . . . . . . . . . . 17 Piping Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . 18 Redirecting Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Using Wildcards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Viewing File Contents with more. . . . . . . . . . . . . . . . . 22 Displaying File Contents with cat. . . . . . . . . . . . . . . . 23 Exploring the System . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Getting Help with man. . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Logging Out. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

Table of Contents

Chapter 3: Working with Your Shell

Discovering Which Shell You’re Using. . . . . . . . . . . . 52 Understanding Shells and Options. . . . . . . . . . . . . . . 53 Changing Your Shell with chsh. . . . . . . . . . . . . . . . . . . 55 Changing Your Shell Temporarily. . . . . . . . . . . . . . . . . 57 Using Completion in the bash Shell . . . . . . . . . . . . . . 59 Viewing Session History in the bash Shell . . . . . . . . 60 Using Completion in the zsh Shell. . . . . . . . . . . . . . . . 62 Viewing Session History in the zsh Shell. . . . . . . . . . 63 Changing Your Identity with su . . . . . . . . . . . . . . . . . . 65 Fixing Terminal Settings with stty. . . . . . . . . . . . . . . 67 Exiting the Shell. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Chapter 4: Creating and Editing Files

Table of Contents

Choosing an Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 Starting pico and Dabbling with It. . . . . . . . . . . . . . . 73 Saving in pico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 Cutting and Pasting Text Blocks in pico. . . . . . . . . . 75 Checking Spelling in pico. . . . . . . . . . . . . . . . . . . . . . . . 76 Getting Help in pico. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 Exiting pico. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 Starting vi and Dabbling with It. . . . . . . . . . . . . . . . . . 79 Saving in vi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Adding and Deleting Text in vi. . . . . . . . . . . . . . . . . . . 82 Importing Files into vi. . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Searching and Replacing in vi. . . . . . . . . . . . . . . . . . . . 84 Exiting vi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 Starting emacs and Dabbling with It. . . . . . . . . . . . . . 87 Using emacs Menus to Spell-Check. . . . . . . . . . . . . . . 89 Saving in emacs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 Exiting emacs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Chapter 5: Controlling Ownership and Permissions

Understanding File Ownership and Permissions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 Finding Out Who Owns What. . . . . . . . . . . . . . . . . . . . 95 Finding Out Which Group You’re In . . . . . . . . . . . . . . 97 Changing the Group Association of Files and Directories with chgrp. . . . . . . . . . . . . . . . . . 99 Changing Ownership of Files and Directories with chown . . . . . . . . . . . . . . . . . . . . 101 Changing Permissions with chmod. . . . . . . . . . . . . . 103 Translating Mnemonic Permissions to Numeric Permissions. . . . . . . . . . . . . . . . . . . 106 Changing Permission Defaults with umask. . . . . . 107

Table of Contents

Chapter 6: Manipulating Files

Chapter 7: Getting Information About the System

Getting System Information with uname . . . . . . . . 134 Viewing File Systems with df. . . . . . . . . . . . . . . . . . . 135 Determining Disk Usage with du . . . . . . . . . . . . . . . 138 Finding Out File Types with file. . . . . . . . . . . . . . . 139 Finding Out About Users with finger. . . . . . . . . . 140 Learning Who Else Is Logged in with who. . . . . . . 143 Learning Who Else Is Logged in with w . . . . . . . . . 144 Getting Information About Your Userid with id. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Chapter 8: Configuring Your Unix Environment 147 Understanding Your Unix Environment . . . . . . . . 148 Discovering Your Current Environment. . . . . . . . 150 Adding or Changing Variables. . . . . . . . . . . . . . . . . . 152 Looking at Your zsh Configuration Files. . . . . . . . 154 Adding to Your zsh Path. . . . . . . . . . . . . . . . . . . . . . . 158 Changing Your zsh Prompt . . . . . . . . . . . . . . . . . . . . 160 Looking at Your bash Configuration Files. . . . . . . 163 Adding to Your bash Path. . . . . . . . . . . . . . . . . . . . . . 166 Changing Your bash Prompt. . . . . . . . . . . . . . . . . . . 168 Setting Aliases with alias . . . . . . . . . . . . . . . . . . . . . 170

Table of Contents

Counting Files and Their Contents with wc . . . . . 110 Viewing File Beginnings with head . . . . . . . . . . . . . 111 Viewing File Endings with tail . . . . . . . . . . . . . . . . 112 Finding Text with grep. . . . . . . . . . . . . . . . . . . . . . . . . 113 Using Regular Expressions with grep. . . . . . . . . . . 114 Using Other Examples of Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . 116 Making Global Changes with sed. . . . . . . . . . . . . . . 117 Changing Files with awk. . . . . . . . . . . . . . . . . . . . . . . . 118 Comparing Files with cmp. . . . . . . . . . . . . . . . . . . . . . 120 Finding Differences in Files with diff. . . . . . . . . . 121 Finding Differences in Files with sdiff. . . . . . . . . 122 Sorting Files with sort. . . . . . . . . . . . . . . . . . . . . . . . . 123 Eliminating Duplicates with uniq . . . . . . . . . . . . . . 125 Redirecting to Multiple Locations with tee. . . . . 126 Changing with tr. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 Formatting with fmt . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Splitting Files with split . . . . . . . . . . . . . . . . . . . . . . 131

Table of Contents

Chapter 9: Running Scripts and Programs

Running a Command. . . . . . . . . . . . . . . . . . . . . . . . . . 174 Scheduling Onetime Jobs with at . . . . . . . . . . . . . . 175 Scheduling Regularly Occurring Jobs with cron . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Suspending Jobs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Checking Job Status with jobs . . . . . . . . . . . . . . . . . 181 Running Jobs in the Background with bg . . . . . . . 182 Running Jobs in the Foreground with fg. . . . . . . . 183 Controlling Job Priority with nice. . . . . . . . . . . . . . 184 Timing Jobs with time . . . . . . . . . . . . . . . . . . . . . . . . . 185 Finding Out What Processes Are Running with ps. . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Deleting Processes with kill . . . . . . . . . . . . . . . . . . 189

Table of Contents

Chapter 10: Writing Basic Scripts

Creating a Shell Script . . . . . . . . . . . . . . . . . . . . . . . . . 192 Running a Shell Script . . . . . . . . . . . . . . . . . . . . . . . . . 194 Making a Script Executable. . . . . . . . . . . . . . . . . . . . 195 Getting a Head Start on Scripts with history. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 Embedding Commands. . . . . . . . . . . . . . . . . . . . . . . . 198 Looping Your Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . 200 Creating If-Then Statements . . . . . . . . . . . . . . . . . . . 202 Accepting Command-Line Arguments in Your Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205 Accepting Input While a Script Is Running . . . . . 206 Debugging Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

Chapter 11: Sending and Reading E-mail

Choosing an E-mail Program and Getting Started . . . . . . . . . . . . . . . . . . . . . . . 210 Reading E-mail with pine. . . . . . . . . . . . . . . . . . . . . . 212 Sending E-mail with pine. . . . . . . . . . . . . . . . . . . . . . 214 Customizing pine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 Reading E-mail with mutt. . . . . . . . . . . . . . . . . . . . . . 218 Sending E-mail with mutt. . . . . . . . . . . . . . . . . . . . . . 220 Reading E-mail with mail. . . . . . . . . . . . . . . . . . . . . . 222 Sending E-mail with mail. . . . . . . . . . . . . . . . . . . . . . 223 Creating a Signature File. . . . . . . . . . . . . . . . . . . . . . . 225 Automatically Forwarding Incoming Messages . . . . . . . . . . . . . . . . . . . . . . . 227 Announcing an Absence with vacation. . . . . . . . 228 Configuring procmail . . . . . . . . . . . . . . . . . . . . . . . . . 230 Managing E-mail with procmail . . . . . . . . . . . . . . . 232

Table of Contents

Chapter 12: Accessing the Internet

Getting Familiar with Unix Internet Lingo. . . . . . 236 Logging in to Remote Systems with ssh . . . . . . . . 238 Logging in to Remote Systems with telnet. . . . . 239 Communicating with Others Using write. . . . . . 241 Communicating with Others Using talk . . . . . . . 242 Getting Files from the Internet with ftp. . . . . . . . 243 Sharing Files on the Internet with ftp. . . . . . . . . . 247 Surfing the Web with links. . . . . . . . . . . . . . . . . . . . 249 Surfing the Web with lynx . . . . . . . . . . . . . . . . . . . . . 251 Downloading Web Sites with wget . . . . . . . . . . . . . 253 Checking Connections with ping . . . . . . . . . . . . . . 254 Tracing Connections with traceroute. . . . . . . . . 255 Matching Domain Names with IP Addresses . . . 257

Encoding Files with uuencode. . . . . . . . . . . . . . . . . . 260 Decoding Files with uudecode. . . . . . . . . . . . . . . . . . 263 Archiving with tar. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 Unarchiving Files with tar. . . . . . . . . . . . . . . . . . . . . 266 Compressing Files with compress. . . . . . . . . . . . . . 267 Uncompressing Files with uncompress. . . . . . . . . 268 Zipping a File or Directory with gzip. . . . . . . . . . . 269 Unzipping a gzip File with gunzip . . . . . . . . . . . . . 270 Zipping Files and Directories with zip . . . . . . . . . 271 Unzipping Zipped Files with unzip. . . . . . . . . . . . . 272 Combining Commands. . . . . . . . . . . . . . . . . . . . . . . . 273

Chapter 14: Using Handy Utilities

Calendaring with cal . . . . . . . . . . . . . . . . . . . . . . . . . . 276 Calculating with bc . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 Evaluating Expressions with expr. . . . . . . . . . . . . . 280 Converting with units. . . . . . . . . . . . . . . . . . . . . . . . . 281 Looking It Up with look. . . . . . . . . . . . . . . . . . . . . . . . 282 Keeping a Record of Your Session with script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

Table of Contents

Chapter 13: Working with Encoded and Compressed Files

Table of Contents

Chapter 15: Being Root

Acting Like root with sudo. . . . . . . . . . . . . . . . . . . . . 288 Becoming root with su . . . . . . . . . . . . . . . . . . . . . . . . 290 Starting, Stopping, and Restarting Daemons. . . . 292 Changing the System Configuration. . . . . . . . . . . . 294 Monitoring the System. . . . . . . . . . . . . . . . . . . . . . . . . 296 Keeping up with watch. . . . . . . . . . . . . . . . . . . . . . . . . 299 Checking Boot Messages with dmesg . . . . . . . . . . . 300 Setting the Date and Time . . . . . . . . . . . . . . . . . . . . . 302

Chapter 16: Sensational Unix Tricks

Table of Contents

Cleaning Up HTML Documents with tidy . . . . . 304 Searching and Replacing Throughout Multiple Documents with sed . . . . . . . . . . . . . 307 Generating Reports with awk. . . . . . . . . . . . . . . . . . . 310 Using Input to Customize Your Environment. . . . . . . . . . . . . . . . . . . . . . . . . 311 Using ROT13 Encoding with sed . . . . . . . . . . . . . . . 313 Embedding ROT13 Encoding in a Shell Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 Making Backups with rsync . . . . . . . . . . . . . . . . . . . 318 Using Advanced Redirection with stderr . . . . . . 320

Appendix A: Unix Reference

Appendix B: What’s What and What’s Where

Appendix C: Commands and Flags

Greetings, and welcome to Unix and Linux!

For the purposes of this book, Unix and Linux are pretty much interchangeable—the commands and usages are the same. You may find small differences among Unix versions or between specific Unix or Linux versions, but they’ll be small indeed.

In this book, you’ll find the information you need to get started with the operating system, advance your skills, and make Linux or Unix do the hard work for you. This book focuses on the most common Unix and Linux commands, but it also gives you ideas for working smartly and efficiently.

How Do You Use This Book?

How Do You Use This Book?

We designed this book to be used as both a tutorial and a reference. If you’re a Unix newbie, you should start at the beginning and work forward through the first several chapters. As you progress through the chapters, you’ll build on concepts and commands you learned in previous chapters. Then, as you become more proficient, you can start choosing topics, depending on what you want to do. Be sure to reference the table of contents, index, and the appendixes to find information at a glance. The commands used throughout this book apply to any version of Unix (or Linux) you might be using, including OpenSolaris, BSD, Solaris through your local Internet service provider, Linux, AIX or HP-UX at work, your Mac OS X or Linux system at home, or any other flavor (that’s the technical term) you can find. Heck, you can even run Unix from your Windows system with Cygwin or VirtualBox. You’ll find more about flavors and getting access to Unix in Chapter 1. Each chapter covers several topics, each of which is presented in its own section. Each section begins with a brief overview of the topic, often including examples or descriptions of how or when you’d use a command. Next, you’ll find a step-by-step list (or a couple of them) to show you how to complete a process. Note that the code you type appears as the numbered step, and a description follows it, like this: 1.

The code you type will appear like  this in a blocky font.

An explanation will appear like this in a more regular font. Here, we often describe what you’re typing, give alternatives, or provide cross-references to related information.

If a line of code in a numbered step is particularly long, the code might wrap to a second line. Just type the characters shown, without pressing e until the end of the command. Also, in code listings throughout the book, a single line of code on screen might wrap to two lines in the book. If this happens, the continued line will start with a  , so it might look like this: The beginning of the code starts here  but it continues on this line.

Sometimes you’ll have to press a special key or key combination—like cC , which means to hold down the c key and press C . We’ll use this special keyboard font for these keys, but not for multiple letters, or numbers, or symbols you might type. Finally, most sections end with a couple of handy tips. Look here for ways to combine Unix commands, suggestions for using commands more efficiently, and ideas for finding out more information.

Bonus Chapter Online You can download an additional chapter of this book, titled “Compiling and Installing Your Own Software,” for free from the publisher’s Web site. Simply register for a free account at http://peachpit.com, and then, while signed in and at your Account page, register the book using its ISBN, 0321636783. After you register the book, a link to the additional content will be listed on your Account page under Registered Products. You can also access the book’s Web page directly at www.peachpit.com/unixlinuxvqs.

Who Are You? We assume that you’ve picked up this book because you already have a need for or an interest in learning to use Unix, or any Unix-like operating system, like Linux, OpenSolaris, Mac OS X, BSD, HP -UX, AIX, Solaris, or others. We assume that You want to know how to use Unix to do things at work, school, or home.

You may or may not already have experience with Unix.

You don’t necessarily have other geeky—er, um, techie—computer skills or experience.

You want to learn to use Unix, but probably do not want to delve into all of the arcane details about the Unix system.

In short, we assume you want to use Unix to achieve your computing goals. You want to know what you can do, get an idea of the potential that a command offers, and learn how to work smart. Very smart. You can do all of these things using this book. Basically, all you need is access to a Unix account or system and a goal (or goals) that you want to achieve.

Use Cygwin to run Unix as part of your Windows environment

Use VirtualBox or other similar programs to run Unix in a “virtual machine” as an application in your Windows environment

Use a bootable Unix (Linux or OpenSolaris) CD to experiment without having to install anything at all on your computer

What Do You Need to Know to Get Started? As you get started learning Unix, keep in mind the following Unix conventions for typing commands: 

Unix terminology and commands are typically arcane, cryptic, and funny looking. For example, the command to list files or directories is just ls—short and cryptic. We’ll walk you through the commands one step at a time, so you know how to read them and apply them to your own uses. Just follow the steps in the order provided.

Unix is case sensitive, so type commands following the capitalization used in the book.

Whenever you type a command, you also have to press e . For example, if we say

What Do You Need Computer-Wise? Computer-wise, you can learn or experiment with Unix using virtually any computer you might have available. If you’re using a Mac with OS X or later, you’re all set; it’s all Unix under the hood. If you have an extra computer sitting around, even something as old as a Pentium III, you can install several different flavors of Unix or Linux, including OpenSolaris, or Ubuntu, Redhat, or SuSE. Certainly you can install Unix on an extra hard drive (or empty space on your current hard drive) on your regular desktop computer, and generally without affecting your existing Windows configuration.

1. funny-looking command goes here you’ll type the code, then press e , which sends the command along to the Unix system.

How Do You Use This Book?

Alternatively, you can dabble in Unix less invasively by using an account on a system at work, or through an Internet service provider. Probably the easiest options, though, if you have a reasonably new computer and are concerned about not messing up what you have, are

How Do You Use This Book?

Often, we’ll tell you to press a combination of keys on the keyboard, as in cV . Here, all you do is press the c key plus the (lowercase) V key, both at the same time (sequentially is fine also). Even though the keyboard uses capital letters (and, thus, the little key icons also do in this book), you would not take the extra step to capitalize the V (or whatever) in applying key combinations. 

Some commands have flags associated with them (you might think of flags as options for the command) that give you additional control. For example, you might see the ls command used in variations like ls -la or ls -l -a. In either case, ls lists the files in a directory, the optional -l flag specifies that you want the long format, and the optional -a flag specifies all files, including hidden ones (don’t worry, we’ll go over this again!). Just keep in mind that flags are essentially options you can use with a given command.

You can also put multiple commands on the same line. All you have to do is separate the commands with a semicolon (;), like this: ls ; pwd

which would list the files in the current directory (ls) and find out what directory you’re in (pwd)—all in one step! So, with these things in mind, see you in Chapter 1!

Anything Else You Should Know? Yup! Please feel free to send us a message at [email protected]. We welcome your input, suggestions, and questions related to this book. Thanks, and we look forward to hearing from you!

Note to Mac Users For simplicity, we consistently write e (not r ), c (not C ), a (not o ), and we refer (not very often, though) to a Recycle Bin (not a Trash Can). No slight intended to those who do not use PCs or Windows—we just tried to keep the complexity of the instructions to a minimum.

Getting Started with Unix

Accessing a Unix system

Connecting to the Unix system

Changing your password

Listing directories and files

Finding out where you are in the directory tree

Piping input and output

Viewing file contents

Displaying file contents

Exploring the system

Getting Started with Unix

To start you on your journey through Unix, we’ll take a quick look at a few basic concepts and commands. In this chapter, we’ll get you started with basic Unix skills, such as accessing a Unix account, logging in, and listing and viewing files and directories, among other things. We’ll also show you how to explore Unix, see its capabilities, and discover just what you can do with it.

Getting Started with Unix

This chapter is essential for all Unix guruwannabes. If you’re a Unix novice, you should start at the beginning of this chapter and work through each section in sequence. With these basic skills mastered, you can then skip through this book and learn new skills that look useful or interesting to you. If you’ve used Unix before, you might peruse this chapter to review the basics and dust off any cobwebs you might have. The skills covered in this chapter apply to any version of Unix you might be using, including Linux, Solaris, or BSD through your local Internet service provider (ISP); Solaris, AIX, Linux or HP-UX at work; your Mac OS X or Linux system at home; CygWin or Unix through VMware or Unix from a bootable CD on your home system; or any other flavor (that’s the technical term) you can find. Keep in mind, though, that the exact output and prompts you see on the screen might differ slightly from what is illustrated in this book. The differences probably won’t affect the steps you’re completing, although you should be aware that differences could exist. (As much as possible, our examples will give you a sample of the diversity of Unix systems.)

Getting Started with Unix

Accessing a Unix System

People choose to use Unix for a number of reasons: 

Control: Unix offers users more control and customization on the legal and licensing side as well as the “getting stuff done” side.

Economy: Many flavors of Unix offer free or nearly free licensing.

Power: Experienced Unix geeks can do more with less effort on Unix than Windows—for many things, at least.

In the final analysis, though, most Unix people end up sticking with Unix because they tried it, slogged through the initial learning curve, and then decided they like it.

Accessing a Unix System

Using a Unix system is different from working on a PC. Using a PC, the computer’s hard drive is your personal space, and—generally—you don’t have access to what’s on someone else’s hard drive. With Unix, you have your own personal space that’s located within a much bigger system. You might think of Unix as an apartment building, with lots of individual apartment spaces, a central office, and perhaps other general spaces, like a maintenance office. With Unix, you have the entire system that houses dozens, hundreds, or even thousands of personal spaces as well as private spaces ( for, say, the system administrator, bosses, or IT [Information Technology] department staff). You can access your apartment only, but the system administrator (or designated people with authorization) can access any apartment.

Different types of Unix access

Accessing a Unix System

So, the first question is how you might access a Unix system to get started with all of this. Given that this is Unix, you have exactly 1.2 bazillion options. Let’s look at these options: 

Connect to a shell account

Access your company’s (or school’s or organization’s) Unix system

Use a live CD, such as an Ubuntu or OpenSolaris CD

Do a Unix installation in a virtual machine on your computer

Do a Unix-only installation on an old or spare computer

Do a Unix/Windows installation on your everyday computer

Accessing a shell account The traditional approach (back in the olden days, when we wrote the first version of this book) was to connect to a “shell account” provided by your dial-up ISP. That’s still an option, if you have certain ISPs (and even with some broadband connections). If your ISP offers a shell account, go ahead and use it; it’s still a good option. Try Googling “Unix shell account” as well.

Accessing your company’s system If not (that is, if you have a cable modem, DSL connection, or dial-up connection through any of the huge companies that provide Internet access, “not” is the case), you still have a ton of options. Check at work; many companies use Unix in a number of ways, and if you can provide the system administrator with appropriate quantities of cookies or other goodies, you may be able to get Unix system access.

Getting Started with Unix

Installing Unix on an old or spare computer Alternatively, if you’d rather keep your Unix explorations closer to home, you can manage that as well. If you have an older computer sitting around (say, anything that’s a Pentium III or later), you can just install Unix (Linux, Solaris, or whatever) on that, and likely without hassles or problems. You could make it work on even older computers, but given how cheap new and used computers are, it’s likely not worth the trouble. Either way, you’ll download a CD or DVD from the Web, burn it onto a disc, and boot your system with the disc in the drive. The installation will start, and a few questions and few minutes later, you’ll be all set.

You can also download the CD or DVD and install on your everyday desktop computer. Most of the time (actually virtually all the time, but we’re making no promises here), you can install Unix onto your desktop right alongside your Windows environment without breaking anything. You’ll get it installed, reboot your system, and choose Unix (Linux, OpenSolaris, whatever) or Windows when you boot up. This option isn’t bad, but it does require you to stop what you’re doing in Windows or Unix to change to the other. If your desktop computer is relatively old, this might be better than the following options, though. If you have a pretty beefy desktop computer (relatively new with ample memory and disk space), you could try using Sun Microsystems’ VirtualBox or VMWare, VirtualPC, or other virtualization environments, which give you computer emulation (think “picture in picture” for your computer, but with one operating system within the other operating system). continues on next page

Accessing a Unix System

Installing Unix and Windows side by side

Chapter 1 Many of the examples and screenshots for this book were taken from Unix systems running under VirtualBox on one of our desktop systems. Cygwin provides you with a Unix environment that’s actually part of your Windows system. It takes a bit of getting used to, but Cygwin is stable and reliable. The hardest part about using Cygwin is that it can be confusing to know whether you’re dealing with Unix or Windows at any given moment.

Different Unix flavors

Accessing a Unix System

So, given all of those options for getting access to Unix, the choice of which kind of Unix (which Unix flavor) must be clear and straightforward—right? Of course not. If you’re just getting started with Unix, we recommend having you choose the flavor that your most techie friends or the folks at work use. This will give you potential built-in tech support options. If you’re starting purely from scratch, look into the most popular and highly rated Linux distributions. (Currently, the Web site www.distrowatch.com provides a great set of recommendations, but as you know, Web sites change, so you might want to also do some Web searching for recommended Linux distributions.) A newly popular (or popular again) option is OpenSolaris, from Sun Microsystems. For a while Solaris was a bit tricky (well, a lot tricky) to get installed and functional on a regular desktop system; however, it’s now as easy as the easier Linux systems, and it offers a tremendous amount of power and flexibility, in addition to some cutting-edge technologies. That said, any option you choose will be pretty similar for the purposes of this book. Differences among the options primarily show up in more advanced applications.

If you’re using Mac OS X or later, you’re already using Unix—you just need to bring up a terminal window to be able to follow right along with the book.

Getting Started with Unix

Connecting to the Unix System About Connecting

Yes, we know, you don’t have any secrets, but if a hacker logs into your ISP’s system as you, that same hacker has won 50 percent of the battle for taking over that system for any number of illegal activities. And, if your neighbor’s 19-year-old son sniffs (that’s the technical term) your user identification (often called the userid or user ID) and password over your cable modem connection (and that’s entirely possible), he can probably guess that your eBay password, broker password, or whatever are the same or at least similar. Throughout this book, we’ll show examples using an ssh connection. If, for whatever reason, your system administrators don’t require ssh, we recommend using it anyway; there is absolutely no reason not to, because there are no disadvantages to ssh compared to telnet. If your systems don’t support ssh, you can use the telnet or rlogin/rsh program as alternatives.

To connect to the Unix system: 1. Connect to the Internet, if necessary. If you have to start your Internet connection manually, launch it now. If you use a fulltime Internet connection at home, work, or school, or if you’re using your Mac or Linux system at home, just ignore this step. 2. If you’re connecting to a remote system, start your ssh program and connect to the Unix system. Using ssh you can connect to a remote computer (such as your ISP’s computer) and work as if the remote computer were sitting on your desk. Essentially, ssh brings a remote computer’s capabilities to your fingertips, regardless of where you’re physically located. (See the “About Connecting” sidebar for more information about connection technologies.) Exactly how you connect depends on the particular program you’re using. For Windows users, we recommend PuTTY, which is a free ssh client available at www. chiark.greenend.org.uk/~sgtatham/ putty/. For Macintosh users (pre–OS X), we recommend the predictably named MacSSH, also free, available at http:// sourceforge.net/projects/macssh.

continues on next page

Connecting to the Unix System

Once upon a time, when dinosaurs roamed the earth, Unix users connected to their systems using telnet. With telnet, your password and everything else you do is sent straight across the wire and can be easily read by anyone on the same part of the network. Yikes is right! That’s why, more and more, ISPs and system administrators require something called ssh (Secure SHell) to connect to their systems. With ssh, everything is encrypted, precisely the way your Web connection is encrypted when you use an e-commerce site and see that the little padlock in your Web browser is closed.

Your first step in using Unix is to connect to the Unix system. Exactly how you connect will vary depending on what kind of Internet connection you use, but the following steps should get you started.

Connecting to the Unix System

And, of course, after you’re logged into your Unix-like system, you can use the Unix ssh command to access other computers. Each program works a bit differently, and you’ll have to refer to the specific documentation for details about using them. In this example, we’re connecting to a Unix system using PuTTY. Figure 1.1 shows the Configuration dialog box, in which we’ve specified Host Name ( frazz.raycomm.com), Port (22), and Protocol (ssh). If you’re looking for a quick start, just fill in the fields shown in Figure 1.2 and click Open. 3. Alternatively, if you’re on a Mac or Linux or Unix system already, just open a terminal window and you’ll be all set—and you won’t even have to log in. 4. Check out the Categories (or the Preferences dialog box in many other programs) and become familiar with your options. You will not need to change anything initially, but you might later want to customize colors or other settings. Generally, though, PuTTY provides usable settings. 5. Marvel at the login: prompt, which is what you should see if you’ve connected properly (Figure 1.3) and move along to the next section. (PuTTY displays “login as :”, while most other programs will just show you “login:”. Don’t worry about this difference; it’s just this program’s idiosyncrasy.)

Figure 1.1 Here we’re connecting to frazz.raycomm. com using PuTTY. Other ssh programs might look slightly different, but this shows the general idea.

Figure 1.2 For a quick start, fill in these fields, and then click Open.

Figure 1.3 PuTTY shows a login as: prompt from frazz.raycomm.com.

Getting Started with Unix

Before You Begin Before you begin, have your connection information, such as your login name and password, handy. Contact your system administrator if you don’t yet have these. Throughout this book, we’ll use “system administrator” to refer to your help desk, ISP technical support line, or anyone else you can call on who runs your Unix system and can help you. Sometimes that geeky daughter, brother, or otherwise Unixy-person can help you out with Unix, too; however, in many cases you’ll find that you need to troubleshoot a problem with the person who can manage your account information.

If you modify the connection settings, you may need to disconnect from the session, then reconnect again for the new settings to take effect. See your documentation for specifics about disconnecting from your session.

In addition to viewing the buffer to see commands you’ve used, as mentioned in the “The SSH Preferences Dialog Box” sidebar (later in this chapter), you can also use a command to let you review commands that you’ve issued. For more information, see the appropriate “Viewing Session History” section in Chapter 3.

Connecting to the Unix System

Write Down Details About Your Specific login Procedure As you go through your login procedure, take a minute to write down some details for future reference. Your userid or login name (but not your password): __________________________________________________________________________ The name of the program you use (or the icon you click) to connect to your Unix system and the process you use to get connected: __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________ __________________________________________________________________________ The name of your Unix system (such as frazz.example.com or example.com): __________________________________________________________________________ The IP (Internet Protocol) address of your Unix system (such as 198.168.11.36 or 10.10.22.2): __________________________________________________________________________

Logging In After you’ve connected to the Unix system, your next step is to log in, or identify yourself to the Unix system. Logging in serves a few purposes, including giving you access to your e-mail, files, and configurations. It also keeps you from inadvertently accessing someone else’s files and settings, and it keeps you from making changes to the system itself.

Figure 1.4 Our Unix system (frazz.raycomm.com) greets us with a quote of the day, called a “fortune.”

1. Have your userid (user identification) and password ready. Contact your system administrator if you don’t have these yet.

2. Type your userid at the login prompt, then press e . Your userid is case sensitive, so be sure you type it exactly as your system administrator instructed. 3. Type your password at the password prompt, then press e . Yup. Your password is case sensitive, too.

Figure 1.5 Some systems might greet you with system information or helpful tips.

4. Read the information and messages that come up on the screen. The information that pops up—the message of the day—might be just funny or lighthearted, as in Figure 1.4, or it might contain information about system policies, warnings about scheduled downtime, or useful tips, as shown in Figure 1.5. It may also contain both, or possibly neither, if your system administrators have nothing to say to you.

After you’ve logged in, you’ll see a shell prompt, which is where you type in commands. Also, note that you’ll be located in your home directory, which is where your personal files and settings are stored. Your “location” in the Unix system is a slightly unwieldy concept that we’ll help you understand throughout this chapter.

If you get an error message after attempting to log in, just try again. You likely just mistyped your userid or password. Whoops!

When you log in, you might see a message about failed login attempts. If you unsuccessfully tried to log in, then don’t worry about it; the message just confirms that you attempted to log in but failed. If, however, all of your login attempts (with you sitting at the keyboard) have been successful or if the number of failed login attempts seems high—say, five or more— then you might also mention the message to your system administrator, who can check security and login attempts. This could be a warning that someone unauthorized is trying to log in as you.

Getting Started with Unix $ passwd Changing password for ejr (current) Unix password: New UNIX password: Retype new UNIX password: passwd: all authentication tokens updated

Code Listing 1.1 Change your password regularly using the passwd command.

In the SSH Preferences dialog box, you can fix some of the idiosyncrasies that are caused by how your ssh program talks to the Unix system. You can’t identify these idiosyncrasies until you actually start using your Unix system, but you should remember that you can fix most problems here. For example: 

If your N and D keys don’t work, look for an option in your ssh or telnet program that defines these keyboard functions. If you start typing and nothing shows up onscreen, set local echo to on.

If you start typing and everything shows up twice, set local echo to off.

If you want to be able to scroll up onscreen to see what’s happened during your Unix session, change the buffer size to a larger number.

Exactly which options you’ll have will vary from program to program, but these are ones that are commonly available. Click OK when you’re done playing with the settings.

Virtually all Unix systems require passwords to help ensure that your files and data remain your own and that the system itself is secure from hackers and crackers (malicious hackers). Code Listing 1.1 shows how you change your password. Throughout your Unix adventure, you’ll likely change your password often: 

You’ll probably want to change the password provided by your system administrator after you log in for the first time. Hint, hint.

You’ll probably change your password at regular intervals. Many Unix systems require that you change your password every so often—every 30 or 60 days is common.

You might also change your password voluntarily if you think that someone might have learned it or if you tell anyone your password (although you really shouldn’t do that anyway).

To change your password: 1.

To start, type passwd. 2.

Enter your old password—the one you’re currently using. (Of course, type in your old password, not the sample one we’ve used here!) Note that the password doesn’t show up onscreen when you type it, in case someone is lurking over your shoulder, watching you type, and asking, “Whatcha doing?” continues on next page

Changing Your Password with passwd

The SSH Preferences Dialog Box

Changing Your Password with passwd

Type your new password. Check out the “Lowdown on Passwords” sidebar for specifics about choosing a password. 4.

Here, you’re verifying the password by typing it again. The system will report that your password was successfully changed (specific terminology depends on the system) after the changes take effect. This is also shown in Code Listing 1.1.

 Tips Changing Your Password with passwd

Double-check your new password before you log out of the system by typing su — yourid at the prompt. Of course, substitute your real username (or login name) for yourid here. This command (switch user) lets you log in again without having to log out, so if you made a mistake when changing your password and now get a failed login message, you can find out before you actually disconnect from the system. If you have problems, contact your system administrator before you log out so you can get the problem resolved. In some environments, you will use yppasswd, not passwd, to change your password, or even use a Web page or other means. When in doubt, defer to what your system administrator told you to do. (“The Rays said to use this other command” is likely to get all of us in trouble.)

The Lowdown on Passwords In addition to following any password guidelines your system administrator mandates, you should choose a password that is 

At least six characters long

Easy for you to remember

Not a word or name in any dictionary in any language

A combination of capital and lowercase letters, numbers, and symbols

Not similar to your username

Not identical or similar to one you’ve used recently

Not your telephone number, birth date, kid’s birth date, anniversary (even if you can remember it), mother’s maiden name, or anything else that someone might associate with you

Getting Started with Unix

Listing Directories and Files with ls Your Unix system is made up of directories and files that store a variety of information, including setup information, configuration settings, programs, and options, as well as other files and directories. You might think of your Unix system as a tree (tree roots, actually), with subdirectories stemming from higher-level directories. As shown in Figure 1.6, all of these files and directories reside within the root directory, which contains everything in the system.

To list the files and directories of the directory you’re in:  ls

At the shell prompt, type ls to list the files and directories in the current directory, which in this case is our home directory (Code Listing 1.2).

Figure 1.6 All files and directories are nested within the root directory, which serves to contain everything in the system.

[jdoe@frazz jdoe]$ ls limerick

Code Listing 1.2 Use ls by itself to list the files and subdirectories of the directory you’re in.

Listing Directories and Files with ls

Using the ls command, you can find out exactly what’s in your Unix system and thereby find out what’s available to you. You can list the files and directories of a directory that you’re currently in or a directory that you specify.

To list the files and directories of a specified directory:  ls /bin

Here, you type the ls command plus the name of a directory. As shown in Code Listing 1.3, this command lists the files and directories in the /bin directory, in which you’ll find system commands and programs.

Listing Directories and Files with ls

You can list the files and directories of the root directory at any time and in any place by typing ls /. The root directory is the highest-level directory in a Unix system; all other directories are below the root directory.

Can’t remember that pesky filename? Just use ls to help jog your memory. Or, refer to “Finding Forgotten Files with find” in Chapter 2, which can also help you remember filenames.

Many other ls options are available to control the amount of information about your files that you see and the format in which they appear onscreen. See Chapter 2’s “Listing Directories and Files with ls (More Goodies)” section for details.

[jdoe@frazz jdoe]$ ls /bin arch*

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *