Unix Frequently Asked Questions

This FAQ answers frequent questions related to the Unix operating system. If you have questions related to the ["BASH"] shell, the BashFaq is a better place to look.

TableOfContents

Anchor(faq1)

1. How can I get the IP address for a host name?

Depending on where the (host, ip_address) relationship is stored, different ways of resolving a host name to an ip address (or vice versa) exist. The most common ones are /etc/hosts, NIS, and DNS. As if that wasn't enough, many systems use more than one method, usually configured in the file /etc/nsswitch.conf.

In the easiest case the system has the getent command, which will use /etc/hosts, NIS, DNS, or whatever name resolution was configured in the right sequence:

    $ getent hosts www.shelldorado.com
    127.0.0.1   www.shelldorado.com

If we don't have this very useful command (_XXX is there an OpenSource version available?_), we are on our own and have to access the respective database ourselves. Note that we don't show here how to find out which name resolutions are configured, or in which sequence they are used.

1.1. /etc/hosts

1.2. NIS - Network Information System, also known as Yellow Pages

1.3. DNS - Domain Name Service

1.4. LDAP - Lightweight Directory Access Protocol

Anchor(faq2)

2. How can I copy a directory with all files and subdirectories?

    src=/home/$USER         # source
    dst=/tmp/backup         # destination

    cd "$src"
    find . -print | cpio -pdmv "$dst"

This method can be used to receate a directory hierarchy, without files, too:

    find . -type d -print | cpio -pdmv "$dst"

Anchor(faq3)

3. How can I remove a file with a name starting with '-'?

Either

    rm ./-filename

(./ is the name of the current directory). Another way (for newer Unix systems):

    rm -- -filename

The "--" argument is a standard way to denote the end of the command line options.

Anchor(faq4)

4. How can I redirect the output of the time(1) command?

time is a special command that writes to standard error (file descriptor 2). It's not possible to directly redirect its output to a file, e.g.

    time ls 2>time.out

would only redirect the ls standard error output, not the time output. A solution is to either call time in a subshell with redirected output, e.g.

    sh -c "time ls" 2>time.out

or use braces:

    { time ls; } 2>time.out