Difference between pages "Metro Quick Start Tutorial/pt-br" and "Linux Fundamentals, Part 1/pt-br"

From Funtoo
< Metro Quick Start Tutorial(Difference between pages)
Jump to navigation Jump to search
 
(Created page with "{{Article |Author=Drobbins |Next in Series=Linux Fundamentals, Part 2 }} == Antes de Iinciar == === About this tutorial === Bem vindo ao "Linux fundamentals," o primeiro de q...")
 
Line 1: Line 1:
= Prefácio =  
{{Article
 
|Author=Drobbins
== Como o Metro Funciona ==  
|Next in Series=Linux Fundamentals, Part 2
 
}}
Você pode estar se perguntando como o [[Metro]] cria seu primeiro stage tarball. Como você pode ter imaginado, [[Metro]] não pode criar um stage tarball. Para construi um novo stage tarball, [[Metro]] deve utilizar um já existente, antigo stage tarball chamado de uma &quot;seed&quot; stage. Essa semente &quot;semente&quot; stage tipicamente é utilizado com o ''ambiente build'' para a criação do stage que queremos.
== Antes de Iinciar ==


[[Metro]] pode utilizar dois tipos de semente stages. Tradicionalmente, [[Metro]] tem utilizado um stage3 como uma semente stage. Esse stage3 é então utilizado para construir um novo stage1, que em troca é utlilizado para construir um novo stage2, e então um novo stage3. Esse é geralmente o jeito mais confiável de construir [[Gentoo Linux]] ou [[Funtoo Linux]], entao essa é a recomendação recomendada.
=== About this tutorial ===
{{fancyimportant|'''Depois de portar o metro builds para o perfil do Funtoo, os stages do Gentoo não são mais fornecidos'''!}}
Bem vindo ao "Linux fundamentals," o primeiro de quatro tutoriais desenvolvido para lhe preparar para o exame da Linux Professional Institute's 101 (LPI 101). Nesse tutorial, vamos lhe introduzir ao bash (o shell padrão do Linux), lhe mostrar como tirar vantagem dos comando padrões do Linux como like ls, cp, e mv, explicar inodes e hard links e links simbólicos, e muito mais. Ao final desse tutorial, você terá sólida base no Linux fundamentals e estará até mesmo pronto para começar a aprender algumas tarefas básicas de administração do sistema Linux. Ao final dessa série de tutoriais (oito ao todo), você terá conhecimento que você precisa para se tornar um administrador Linux e estará pronto para realizar uma certificação LPIC nível 1 da Linux Professional Institute se você escolher assim.


== Sementes e Build Isolation ==
Esse tutorial particular (Parte 1) é ideal para aqueles que são novos no Linux, ou para aqueles que querem rever ou melhorar seus entendimentos dos conceitos fundamentais do Linux como copiar e mover arquivos, criar symbolic e hard links, e utilizar comandos de processamento de texto padrão do Linux juntamente com pipelines e redirecionamento. Ao longo do caminho, compartilharemos um monte de sugestões, dicas, e truques para manter o tutorial robusto e prático, mesmo para aqueles com uma bom montante de experiencia anterior em Linux. Para iniciantes, muito desse será novo, mas usuários de Linux mais experientes podem achar esse tutorial ser um ótimo jeito de circundar suas habilidades fundamentais em Linux.


Um outro conceito importante a mencionar aqui é algo chamando de ''build isolation''. Por que o [[Metro]] cria um ambiente build isolado, e o ambiente build é explicitamente definido utilizando entidades existentes, tangíveis -- uma semente stage e um portage snapshot -- você obterá resultados consistentes, repetíveis. Em outras palavras, a mesma semente stage, portage snapshot e instrções build gerarão resultados identico, mesmo se você desempenhar o um mês mais tarde em algum workstation de outro pessoa.
For those who have taken the release 1 version of this tutorial for reasons other than LPI exam preparation, you probably don't need to take this one. However, if you do plan to take the exams, you should strongly consider reading this revised tutorial.


== Local Build ==  
== Introducing bash ==
=== The shell ===
If you've used a Linux system, you know that when you log in, you are greeted by a prompt that looks something like this:
<pre>
$
</pre>
The particular prompt that you see may look quite different. It may contain your systems host name, the name of the current working directory, or both. But regardless of what your prompt looks like, there's one thing that's certain. The program that printed that prompt is called a "shell," and it's very likely that your particular shell is a program called <span style="color:green">bash</span>.


Say you wanted to build a new <tt>pentium4</tt> stage3 tarball. The recommended method of doing this would be to grab an existing <tt>pentium4</tt> stage3 tarball to use as your seed stage. [[Metro]] will be told to use this existing <tt>pentium4</tt> stage3 to build a new stage1 for the same <tt>pentium4</tt>. For this process, the generic <tt>pentium4</tt> stage3 would provide the ''build environment'' for creating our new stage1. Then, the new stage1 would serve as the build environment for creating the new <tt>pentium4</tt> stage2. And the new <tt>pentium4</tt> stage2 would serve as the build environment for creating the new <tt>pentium4</tt> stage3.
=== Are you running bash? ===
You can check to see if you're running <span style="color:green">bash</span> by typing:
<pre>
$ echo $SHELL
/bin/bash
</pre>
If the above line gave you an error or didn't respond similarly to our example, then you may be running a shell other than bash. In that case, most of this tutorial should still apply, but it would be advantageous for you to switch to <span style="color:green">bash</span> for the sake of preparing for the 101 exam.


In the [[Metro]] terminology this is called a '''local build''', which means a stage3 of a given architecture is used to seed a brand new build of the same architecture. Incidentally this will be the first exercise we are going to perform in this tutorial.
=== About bash ===
Bash, an acronym for "Bourne-again shell," is the default shell on most Linux systems. The shell's job is to obey your commands so that you can interact with your Linux system. When you're finished entering commands, you may instruct the shell to exit or logout, at which point you'll be returned to a login prompt.


A week later, you may want to build a brand new <tt>pentium4</tt> stage3 tarball. Rather than starting from the original <tt>pentium4</tt> stage3 again, you'd probably configure [[Metro]] to use the most-recently-built <tt>pentium4</tt> stage3 as the seed. [[Metro]] has built-in functionality to make this easy, allowing it to easily find and track the most recent stage3 seed available.
By the way, you can also log out by pressing control-D at the bash prompt.


== Remote Build ==  
=== Using "cd" ===
As you've probably found, staring at your bash prompt isn't the most exciting thing in the world. So, let's start using bash to navigate around our file system. At the prompt, type the following (without the <span style="color:green">$</span>):
<pre>
$ cd /
</pre>
We've just told bash that you want to work in /, also known as the root directory; all the directories on the system form a tree, and / is considered the top of this tree, or the root. cd sets the directory where you are currently working, also known as the "current working directory."


[[Metro]] can also perform '''remote build''', where a stage3 of a different, but binary compatible, architecture is used as a seed to build a different architecture stage3. Consequentiality the second exercise we are going to perform in this tutorial will be to build a <tt>core2 32bit</tt> stage3 tarball from the <tt>pentium4</tt> stage3 tarball we have just built.
=== Paths ===
To see bash's current working directory, you can type:
<pre>
$ pwd
/
</pre>
In the above example, the / argument to <span style="color:green">cd</span> is called a ''path''. It tells cd where we want to go. In particular, the / argument is an ''absolute'' path, meaning that it specifies a location relative to the root of the file system tree.


TODO: add caveats about what archs can be seeded and what can be not (maybe a table?)
=== Absolute paths ===
Here are some other absolute paths:
<pre>
/dev
/usr
/usr/bin
/usr/local/bin
</pre>
As you can see, the one thing that all absolute paths have in common is that they begin with /. With a path of /usr/local/bin, we're telling cd to enter the / directory, then the usr directory under that, and then local and bin. Absolute paths are always evaluated by starting at / first.


== Tailored Build ==  
=== Relative paths ===
The other kind of path is called a ''relative path''. <span style="color:green">Bash</span>, <span style="color:green">cd</span>, and other commands always interpret these paths relative to the current directory. Relative paths never begin with a /. So, if we're in /usr:
<pre>
$ cd /usr
</pre>
Then, we can use a relative path to change to the /usr/local/bin directory:
<pre>
$ cd local/bin
$ pwd
/usr/local/bin
</pre>


Last, it's also worthy noting that both in <tt>local</tt> and <tt>remote builds</tt>, [[Metro]] can be configured to add and/or remove individual packages to the final tarball.
=== Using .. ===
Let's say you can't live without <tt>app-misc/screen</tt>, at the end of this tutorial, we will show how to have your tailored stage3 to include it.
Relative paths may also contain one or more .. directories. The .. directory is a special directory that points to the parent directory. So, continuing from the example above:
<pre>
$ pwd
/usr/local/bin
$ cd ..
$ pwd
/usr/local
</pre>
As you can see, our current directory is now /usr/local. We were able to go "backwards" one directory, relative to the current directory that we were in.


== Installing Metro ==
In addition, we can also add .. to an existing relative path, allowing us to go into a directory that's alongside one we are already in, for example:
<pre>
$ pwd
/usr/local
$ cd ../share
$ pwd
/usr/share
</pre>


'''The recommended and supported method''' is to use the Git repository of [[Metro]].
=== Relative path examples ===
Relative paths can get quite complex. Here are a few examples, all without the resultant target directory displayed. Try to figure out where you'll end up after typing these commands:
<pre>
$ cd /bin
$ cd ../usr/share/zoneinfo


Ensure that {{Package|dev-vcs/git}} and {{Package|dev-python/boto}} (optional; required for EC2 support) are installed on your system:


<console>
$ cd /usr/X11R6/bin
# ##i##emerge dev-vcs/git
$ cd ../lib/X11
# ##i##emerge dev-python/boto
</console>


Next, clone the master git repository as follows:


<console>
$ cd /usr/bin
# ##i##cd /root
$ cd ../bin/../bin
# ##i##git clone git://github.com/funtoo/metro.git
</pre>
# ##i##cp /root/metro/metro.conf ~/.metro
Now, try them out and see if you got them right :)
</console>


You will now have a directory called <tt>/root/metro</tt> that contains all the [[Metro]] source code.
=== Understanding "." ===
Before we finish our coverage of cd, there are a few more things I need to mention. First, there is another special directory called ., which means "the current directory". While this directory isn't used with the cd command, it's often used to execute some program in the current directory, as follows:
<pre>
$ ./myprog
</pre>
In the above example, the myprog executable residing in the current working directory will be executed.


Metro is now installed. It's time to customize it for your local system.
=== cd and the home directory ===
If we wanted to change to our home directory, we could type:
<pre>
$ cd
</pre>
With no arguments, cd will change to your home directory, which is /root for the superuser and typically /home/username for a regular user. But what if we want to specify a file in our home directory? Maybe we want to pass a file argument to the <span style="color:green">myprog</span> command. If the file lives in our home directory, we can type:
<pre>
$ ./myprog /home/drobbins/myfile.txt
</pre>
However, using an absolute path like that isn't always convenient. Thankfully, we can use the ~ (tilde) character to do the same thing:
<pre>
$ ./myprog ~/myfile.txt
</pre>


= Configuring Metro =
=== Other users' home directories ===
Bash will expand a lone ~ to point to your home directory, but you can also use it to point to other users' home directories. For example, if we wanted to refer to a file called fredsfile.txt in Fred's home directory, we could type:
<pre>
$ ./myprog ~fred/fredsfile.txt
</pre>


{{Note|Metro is not currently able to build Gentoo stages. See {{Bug|FL-901}}.}}
== Using Linux Commands ==


[[User:Drobbins|Daniel Robbins]] maintains [[Metro]], so it comes pre-configured to successfully build [[Funtoo Linux]] releases. Before reading further, you might want to customize some basic settings like the number of concurrent jobs to fit your hardware's capabilities or the directory to use for produced stage archives. This is accomplished by editing <tt>~/.metro</tt> which is the [[Metro]]'s master configuration file.
=== Introducing ls ===
Now, we'll take a quick look at the ls command. Very likely, you're already familiar with ls and know that typing it by itself will list the contents of the current working directory:
<pre>
$ cd /usr
$ ls
X11R6      doc        i686-pc-linux-gnu  lib      man          sbin  ssl
bin        gentoo-x86  include            libexec  portage      share  tmp
distfiles  i686-linux  info              local    portage.old  src
</pre>
By specifying the -a option, you can see all of the files in a directory, including hidden files: those that begin with .. As you can see in the following example, ls -a reveals the . and .. special directory links:
<pre>
$ ls -a
.      bin        gentoo-x86        include  libexec  portage      share  tmp
..    distfiles  i686-linux        info    local    portage.old  src
X11R6  doc        i686-pc-linux-gnu  lib      man      sbin        ssl
</pre>


Please note that <code>path/install</code> must point to where metro was installed. Point <code>path/distfiles</code> to where your distfiles reside. Also set <code>path/mirror/owner</code> and <code>path/mirror/group</code> to the owner and group of all the files that will be written to the build repository directory, which by default (as per the configuration file) is at <code>/home/mirror/funtoo</code>. The cache directory normally resides inside the temp directory -- this can be modified as desired. The cache directory can end up holding many cached .tbz2 packages, and eat up a lot of storage. You may want to place the temp directory on faster storage, for faster compile times, and place the cache directory on slower, but more plentiful storage.
=== Long directory listings ===
You can also specify one or more files or directories on the <span style="color:green">ls</span> command line. If you specify a file, <span style="color:green">ls</span> will show that file only. If you specify a directory, <span style="color:green">ls</span> will show the ''contents'' of the directory. The -l option comes in very handy when you need to view permissions, ownership, modification time, and size information in your directory listing.


{{file|name=.metro|desc=Metro configuration|body=
In the following example, we use the -l option to display a full listing of my /usr directory.
# Main metro configuration file - these settings need to be tailored to your install:
<pre>
$ ls -l /usr
drwxr-xr-x    7 root    root          168 Nov 24 14:02 X11R6
drwxr-xr-x    2 root    root        14576 Dec 27 08:56 bin
drwxr-xr-x    2 root    root        8856 Dec 26 12:47 distfiles
lrwxrwxrwx    1 root    root            9 Dec 22 20:57 doc -> share/doc
drwxr-xr-x  62 root    root        1856 Dec 27 15:54 gentoo-x86
drwxr-xr-x    4 root    root          152 Dec 12 23:10 i686-linux
drwxr-xr-x    4 root    root          96 Nov 24 13:17 i686-pc-linux-gnu
drwxr-xr-x  54 root    root        5992 Dec 24 22:30 include
lrwxrwxrwx    1 root    root          10 Dec 22 20:57 info -> share/info
drwxr-xr-x  28 root    root        13552 Dec 26 00:31 lib
drwxr-xr-x    3 root    root          72 Nov 25 00:34 libexec
drwxr-xr-x    8 root    root          240 Dec 22 20:57 local
lrwxrwxrwx    1 root    root            9 Dec 22 20:57 man -> share/man
lrwxrwxrwx    1 root    root          11 Dec  8 07:59 portage -> gentoo-x86/
drwxr-xr-x  60 root    root        1864 Dec  8 07:55 portage.old
drwxr-xr-x    3 root    root        3096 Dec 22 20:57 sbin
drwxr-xr-x  46 root    root        1144 Dec 24 15:32 share
drwxr-xr-x    8 root    root          328 Dec 26 00:07 src
drwxr-xr-x    6 root    root          176 Nov 24 14:25 ssl
lrwxrwxrwx    1 root    root          10 Dec 22 20:57 tmp -> ../var/tmp
</pre>
The first column displays permissions information for each item in the listing. I'll explain how to interpret this information in a bit. The next column lists the number of links to each file system object, which we'll gloss over now but return to later. The third and fourth columns list the owner and group, respectively. The fifth column lists the object size. The sixth column is the "last modified" time or "mtime" of the object. The last column is the object's name. If the file is a symbolic link, you'll see a trailing -> and the path to which the symbolic link points.


[section path]
=== Looking at directories ===
install: /root/metro
Sometimes, you'll want to look at a directory, rather than inside it. For these situations, you can specify the <span style="color:green">-d</span> option, which will tell ls to look at any directories that it would normally look inside:
tmp: /var/tmp/metro
<pre>
cache: $[path/tmp]/cache
$ ls -dl /usr /usr/bin /usr/X11R6/bin ../share
distfiles: /var/src/distfiles
drwxr-xr-x    4 root    root          96 Dec 18 18:17 ../share
work: $[path/tmp]/work/$[target/build]/$[target/name]
drwxr-xr-x  17 root    root          576 Dec 24 09:03 /usr
drwxr-xr-x    2 root    root        3192 Dec 26 12:52 /usr/X11R6/bin
drwxr-xr-x    2 root    root        14576 Dec 27 08:56 /usr/bin
</pre>


[section path/mirror]
=== Recursive and inode listings ===
So you can use <span style="color:green">-d</span> to look at a directory, but you can also use <span style="color:green">-R</span> to do the opposite: not just look inside a directory, but recursively look inside all the files and directories inside that directory! We won't include any example output for this option (since it's generally voluminous), but you may want to try a few <span style="color:green">ls -R</span> and <span style="color:green">ls -Rl</span> commands to get a feel for how this works.


: /home/mirror/funtoo
Finally, the <span style="color:green">-i</span> ls option can be used to display the inode numbers of the file system objects in the listing:
owner: root
<pre>
group: repomgr
$ ls -i /usr
dirmode: 775
  1409 X11R6        314258 i686-linux          43090 libexec        13394 sbin
  1417 bin            1513 i686-pc-linux-gnu    5120 local          13408 share
  8316 distfiles      1517 include                776 man            23779 src
    43 doc            1386 info                93892 portage        36737 ssl
  70744 gentoo-x86    1585 lib                  5132 portage.old      784 tmp
</pre>


[section portage]
=== Understanding inodes ===
Every object on a file system is assigned a unique index, called an inode number. This might seem trivial, but understanding inodes is essential to understanding many file system operations. For example, consider the . and .. links that appear in every directory. To fully understand what a .. directory actually is, we'll first take a look at /usr/local's inode number:
<pre>
$ ls -id /usr/local
  5120 /usr/local
</pre>
The /usr/local directory has an inode number of 5120. Now, let's take a look at the inode number of /usr/local/bin/..:
<pre>
$ ls -id /usr/local/bin/..
  5120 /usr/local/bin/..
</pre>
As you can see, /usr/local/bin/.. has the same inode number as /usr/local! Here's how we can come to grips with this shocking revelation. In the past, we've considered /usr/local to be the directory itself. Now, we discover that inode 5120 is in fact the directory, and we have found two directory entries (called "links") that point to this inode. Both /usr/local and /usr/local/bin/.. are links to inode 5120. Although inode 5120 only exists in one place on disk, multiple things link to it. Inode 5120 is the actual entry on disk.


MAKEOPTS: auto
In fact, we can see the total number of times that inode 5120 is referenced by using the <pre>ls -dl</pre> command:
<pre>
$ ls -dl /usr/local
drwxr-xr-x    8 root    root          240 Dec 22 20:57 /usr/local
</pre>
If we take a look at the second column from the left, we see that the directory /usr/local (inode 5120) is referenced eight times. On my system, here are the various paths that reference this inode:
<pre>
/usr/local
/usr/local/.
/usr/local/bin/..
/usr/local/games/..
/usr/local/lib/..
/usr/local/sbin/..
/usr/local/share/..
/usr/local/src/..
</pre>


[section emerge]
=== mkdir ===
Let's take a quick look at the <span style="color:green">mkdir</span> command, which can be used to create new directories. The following example creates three new directories, tic, tac, and toe, all under /tmp:
<pre>
$ cd /tmp
$ mkdir tic tac toe
</pre>
By default, the <span style="color:green">mkdir</span> command doesn't create parent directories for you; the entire path up to the next-to-last element needs to exist. So, if you want to create the directories '''won/der/ful''', you'd need to issue three separate <span style="color:green">mkdir</span> commands:
<pre>
$ mkdir won/der/ful
mkdir: cannot create directory `won/der/ful': No such file or directory
$ mkdir won
$ mkdir won/der
$ mkdir won/der/ful
</pre>
However, mkdir has a handy -p option that tells mkdir to create any missing parent directories, as you can see here:
<pre>
$ mkdir -p easy/as/pie
</pre>
All in all, pretty straightforward. To learn more about the mkdir command, type <span style="color:green">man mkdir</span> to read the manual page. This will work for nearly all commands covered here (for example, <span style="color:green">man ls</span>), except for <span style="color:green">cd</span>, which is built-in to bash.


options: --jobs=4 --load-average=4 --keep-going=n
=== touch ===
Now, we're going to take a quick look at the <span style="color:green">cp</span> and <span style="color:green">mv</span> commands, used to copy, rename, and move files and directories. To begin this overview, we'll first use the <span style="color:green">touch</span> command to create a file in /tmp:
<pre>
$ cd /tmp
$ touch copyme
</pre>
The touch command updates the "mtime" of a file if it exists (recall the sixth column in <span style="color:green">ls -l</span> output). If the file doesn't exist, then a new, empty file will be created. You should now have a '''/tmp/copyme''' file with a size of zero.


# This line should not be modified:
=== echo ===
[collect $[path/install]/etc/master.conf]
Now that the file exists, let's add some data to the file. We can do this using the echo command, which takes its arguments and prints them to standard output. First, the echo command by itself:
}}
<pre>
$ echo "firstfile"
firstfile
</pre>
Now, the same echo command with output redirection:
<pre>
$ echo "firstfile" > copyme
</pre>
The greater-than sign tells the shell to write echo's output to a file called copyme. This file will be created if it doesn't exist, and will be overwritten if it does exist. By typing <span style="color:green">ls -l</span>, we can see that the copyme file is 10 bytes long, since it contains the word firstfile and the newline character:
<pre>
$ ls -l copyme
-rw-r--r--    1 root    root          10 Dec 28 14:13 copyme
</pre>


== Arch and Subarch ==
=== cat and cp ===
To display the contents of the file on the terminal, use the cat command:
<pre>
$ cat copyme
firstfile
</pre>
Now, we can use a basic invocation of the <span style="color:green">cp</span> command to create a copiedme file from the original copyme file:
<pre>
$ cp copyme copiedme
</pre>
Upon investigation, we find that they are truly separate files; their inode numbers are different:
<pre>
$ ls -i copyme copiedme
  648284 copiedme  650704 copyme
</pre>


In the following example we are creating a pentium4 stage 3 compiled for x86-32bit binary compatibility. Pentium4 is a subarch of the x86-32bit architecture. Once you have metro installed you may find a full list of each subarch in your <tt>/root/metro/subarch</tt> directory each subarch will have the file extension .spec
=== mv ===
Example:
Now, let's use the <span style="color:green">mv</span> command to rename "copiedme" to "movedme". The inode number will remain the same; however, the filename that points to the inode will change.
<console>
<pre>
###i## ls /root/metro/subarch
$ mv copiedme movedme
# ls subarch/
$ ls -i movedme
amd64-bulldozer-pure64.spec  armv7a.spec          core-avx-i.spec        i686.spec        pentium.spec
   648284 movedme
amd64-bulldozer.spec        armv7a_hardfp.spec   core2_32.spec          k6-2.spec        pentium2.spec
</pre>
amd64-k10-pure64.spec        athlon-4.spec        core2_64-pure64.spec    k6-3.spec        pentium3.spec
A moved file's inode number will remain the same as long as the destination file resides on the same file system as the source file. We'll take a closer look at file systems in [[Linux Fundamentals, Part 3]] of this tutorial series.
amd64-k10.spec              athlon-mp.spec      core2_64.spec          k6.spec          pentium4.spec
amd64-k8+sse3.spec          athlon-tbird.spec    corei7-pure64.spec      native_32.spec    pentiumpro.spec
amd64-k8+sse3_32.spec        athlon-xp.spec      corei7.spec            native_64.spec    prescott.spec
amd64-k8-pure64.spec        athlon.spec          generic_32.spec        niagara.spec      ultrasparc.spec
amd64-k8.spec                atom_32.spec        generic_64-pure64.spec  niagara2.spec    ultrasparc3.spec
amd64-k8_32.spec            atom_64-pure64.spec  generic_64.spec        nocona.spec      xen-pentium4+sse3.spec
armv5te.spec                atom_64.spec        generic_sparcv9.spec    opteron_64.spec  xen-pentium4+sse3_64.spec
armv6j.spec                  btver1.spec          geode.spec              pentium-m.spec
armv6j_hardfp.spec          btver1_64.spec      i486.spec              pentium-mmx.spec
</console>


= First stages build (local build) =
While we're talking about <span style="color:green">mv</span>, let's look at another way to use this command. <span style="color:green">mv</span>, in addition to allowing us to rename files, also allows us to move one or more files to another location in the directory hierarchy. For example, to move '''/var/tmp/myfile.txt''' to '''/home/drobbins''' (which happens to be my home directory,) I could type:
<pre>
$ mv /var/tmp/myfile.txt /home/drobbins
</pre>
After typing this command, myfile.txt will be moved to '''/home/drobbins/myfile.txt'''. And if '''/home/drobbins''' is on a different file system than /var/tmp, the <span style="color:green">mv</span> command will handle the copying of myfile.txt to the new file system and erasing it from the old file system. As you might guess, when myfile.txt is moved between file systems, the myfile.txt at the new location will have a new inode number. This is because every file system has its own independent set of inode numbers.


To get this all started, we need to bootstrap the process by downloading an initial seed stage3 to use for building and place it in its proper location in <tt>/home/mirror/funtoo</tt>, so that [[Metro]] can find it. We will also need to create some special &quot;control&quot; files in <tt>/home/mirror/funtoo</tt>, which will allow [[Metro]] to understand how it is supposed to proceed.
We can also use the <span style="color:green">mv</span> command to move multiple files to a single destination directory. For example, to move myfile1.txt and myarticle3.txt to /home/drobbins, I could type:
<pre>
$ mv /var/tmp/myfile1.txt /var/tmp/myarticle3.txt /home/drobbins
</pre>


== Step 1: Set up pentium4 repository (local build) ==
== Creating Links and Removing Files ==


Assuming we're following the basic steps outlined in the previous section, and building an unstable funtoo (<tt>funtoo-current</tt>) build for the <tt>pentium4</tt>, using a generic <tt>pentium4</tt> stage3 as a seed stage, then here the first set of steps we'd perform:
=== Hard links ===
We've mentioned the term "link" when referring to the relationship between directory entries (the "names" we type) and inodes (the index numbers on the underlying file system that we can usually ignore.) There are actually two kinds of links available on Linux. The kind we've discussed so far are called hard links. A given inode can have any number of hard links, and the inode will persist on the file system until all the hard links disappear. When the last hard link disappears and no program is holding the file open, Linux will delete the file automatically. New hard links can be created using the <span style="color:green">ln</span> command:
<pre>
$ cd /tmp
$ touch firstlink
$ ln firstlink secondlink
$ ls -i firstlink secondlink
  15782 firstlink    15782 secondlink
</pre>
As you can see, hard links work on the inode level to point to a particular file. On Linux systems, hard links have several limitations. For one, you can only make hard links to files, not directories. That's right; even though . and .. are system-created hard links to directories, you (even as the "root" user) aren't allowed to create any of your own. The second limitation of hard links is that they can't span file systems; which would be the case if the file systems are on separate disk partitions. This means that you can't create a link from /usr/bin/bash to /bin/bash if your / and /usr directories exist on separate disk partitions.


<console>
=== Symbolic links ===
# ##i##install -d /home/mirror/funtoo/funtoo-current/x86-32bit/pentium4
# ##i##install -d /home/mirror/funtoo/funtoo-current/snapshots
# ##i##cd /home/metro/mirror/funtoo/funtoo-current/x86-32bit/pentium4
# ##i##install -d 2011-12-13
# ##i##cd 2011-12-13
# ##i##wget -c http://ftp.osuosl.org/pub/funtoo/funtoo-current/x86-32bit/pentium4/2011-12-13/stage3-pentium4-funtoo-current-2011-12-13.tar.xz
# ##i##cd ..
# ##i##install -d .control/version
# ##i##echo "2011-12-13" > .control/version/stage3
# ##i##install -d .control/strategy
# ##i##echo local >  .control/strategy/build
# ##i##echo stage3 > .control/strategy/seed
</console>


OK, let's review the steps above. First, we create the directory <tt>/home/mirror/funtoo/funtoo-current/x86-32bit/pentium4</tt>, which is where Metro will expect to find unstable <tt>funtoo-current</tt> pentium4 builds -- it is configured to look here by default. Then we create a specially-named directory to house our seed x86 stage3. Again, by default, Metro expects the directory to be named this way. We enter this directory, and download our seed x86 stage3 from funtoo.org. Note that the <tt>2010-12-24</tt> version stamp matches. Make sure that your directory name matches the stage3 name too. Everything has been set up to match Metro's default filesystem layout.
In practice, symbolic links (or symlinks) are used more often than hard links. Symlinks are a special file type where the link refers to another file by name, rather than directly to the inode. Symlinks do not prevent a file from being deleted; if the target file disappears, then the symlink will just be unusable, or broken.


Next, we go back to the <tt>/home/mirror/metro/funtoo-current/x86-32bit/pentium4</tt> directory, and inside it, we create a <tt>.control</tt> directory. This directory and its subdirectories contain special files that Metro references to determine certain aspects of its behavior. The <tt>.control/version/stage3</tt> file is used by Metro to track the most recently-built stage3 for this particular build and subarch. Metro will automatically update this file with a new version stamp after it successfully builds a new stage3. But because Metro didn't actually ''build'' this stage3, we need to set up the <tt>.control/version/stage3</tt> file manually. This will allow Metro to find our downloaded stage3 when we set up our pentium4 build to use it as a seed. Also note that Metro will create a similar <tt>.control/version/stage1</tt> file after it successfully builds an pentium4 funtoo-current stage1.
A symbolic link can be created by passing the -s option to <span style="color:green">ln</span>.
<pre>
$ ln -s secondlink thirdlink
$ ls -l firstlink secondlink thirdlink
-rw-rw-r--    2 agriffis agriffis        0 Dec 31 19:08 firstlink
-rw-rw-r--   2 agriffis agriffis        0 Dec 31 19:08 secondlink
lrwxrwxrwx    1 agriffis agriffis      10 Dec 31 19:39 thirdlink -> secondlink
</pre>
Symbolic links can be distinguished in <span style="color:green">ls -l</span> output from normal files in three ways. First, notice that the first column contains an l character to signify the symbolic link. Second, the size of the symbolic link is the number of characters in the target (secondlink, in this case). Third, the last column of the output displays the target filename preceded by a cute little ->.


We also set up <tt>.control/strategy/build</tt> and <tt>.control/strategy/seed</tt> files with values of <tt>local</tt> and <tt>stage3</tt> respectively. These files define the building strategy Metro will use when we build pentium4 funtoo-current stages. With a build strategy of <tt>local</tt>, Metro will source its seed stage from funtoo-current pentium4, the current directory. And with a seed strategy of <tt>stage3</tt>, Metro will use a stage3 as a seed, and use this seed to build a new stage1, stage2 and stage3.
=== Symlinks in-depth ===
Symbolic links are generally more flexible than hard links. You can create a symbolic link to any type of file system object, including directories. And because the implementation of symbolic links is based on paths (not inodes), it's perfectly fine to create a symbolic link that points to an object on another physical file system; that is, a different disk partition. However, this fact can also make symbolic links tricky to understand.


== Step 2: Building the pentium4 stages ==
Consider a situation where we want to create a link in /tmp that points to /usr/local/bin. Should we type this:
<pre>
$ ln -s /usr/local/bin bin1
$ ls -l bin1
lrwxrwxrwx    1 root    root          14 Jan  1 15:42 bin1 -> /usr/local/bin
</pre>
Or alternatively:
<pre>
$ ln -s ../usr/local/bin bin2
$ ls -l bin2
lrwxrwxrwx    1 root    root          16 Jan  1 15:43 bin2 -> ../usr/local/bin
</pre>
As you can see, both symbolic links point to the same directory. However, if our second symbolic link is ever moved to another directory, it will be "broken" because of the relative path:
<pre>
$ ls -l bin2
lrwxrwxrwx    1 root    root          16 Jan  1 15:43 bin2 -> ../usr/local/bin
$ mkdir mynewdir
$ mv bin2 mynewdir
$ cd mynewdir
$ cd bin2
bash: cd: bin2: No such file or directory
</pre>
Because the directory /tmp/usr/local/bin doesn't exist, we can no longer change directories into bin2; in other words, bin2 is now broken.


Incidentally, if all you wanted to do at this point was to build a new pentium4 funtoo-current stage1/2/3 (plus openvz and vserver templates). You would begin the process by typing:
For this reason, it is sometimes a good idea to avoid creating symbolic links with relative path information. However, there are many cases where relative symbolic links come in handy. Consider an example where you want to create an alternate name for a program in /usr/bin:
<pre>
# ls -l /usr/bin/keychain
-rwxr-xr-x    1 root    root        10150 Dec 12 20:09 /usr/bin/keychain
</pre>
As the root user, you may want to create an alternate name for "keychain", such as "kc". In this example, we have root access, as evidenced by our bash prompt changing to "#". We need root access because normal users aren't able to create files in /usr/bin. As root, we could create an alternate name for keychain as follows:
<pre>
# cd /usr/bin
# ln -s /usr/bin/keychain kc
# ls -l keychain
-rwxr-xr-x    1 root    root        10150 Dec 12 20:09 /usr/bin/keychain
# ls -l kc     
lrwxrwxrwx    1 root    root          17 Mar 27 17:44 kc -> /usr/bin/keychain
</pre>
In this example, we created a symbolic link called kc that points to the file /usr/bin/keychain.


<console>
While this solution will work, it will create problems if we decide that we want to move both files, /usr/bin/keychain and /usr/bin/kc to /usr/local/bin:
# ##i##cd /root/metro
<pre>
# ##i##scripts/ezbuild.sh funtoo-current pentium4
# mv /usr/bin/keychain /usr/bin/kc /usr/local/bin
</console>
# ls -l /usr/local/bin/keychain
-rwxr-xr-x    1 root    root       10150 Dec 12 20:09 /usr/local/bin/keychain
# ls -l /usr/local/bin/kc
lrwxrwxrwx    1 root    root          17 Mar 27 17:44 kc -> /usr/bin/keychain
</pre>
Because we used an absolute path in our symbolic link, our kc symlink is still pointing to /usr/bin/keychain, which no longer exists since we moved /usr/bin/keychain to /usr/local/bin.


If you have a slow machine, it could take several hours to be completed because several "heavy" components like gcc or glibc have to be recompiled in each stage. Once a stage has been successfully completed, it is placed in the <tt>"${METRO_MIRROR}/funtoo-current/x32-bit/pentium4/YYYY-MM-DD"</tt> subdirectory, where <tt>YYYY-MM-DD</tt> is today's date at the time the <tt>ezbuild.sh</tt> script was started or the date you put on the ezscript.sh command line.
That means that kc is now a broken symlink. Both relative and absolute paths in symbolic links have their merits, and you should use a type of path that's appropriate for your particular application. Often, either a relative or absolute path will work just fine. The following example would have worked even after both files were moved:
<pre>
# cd /usr/bin
# ln -s keychain kc
# ls -l kc
lrwxrwxrwx    1 root    root            8 Jan  5 12:40 kc -> keychain
# mv keychain kc /usr/local/bin
# ls -l /usr/local/bin/keychain
-rwxr-xr-x    1 root    root        10150 Dec 12 20:09 /usr/local/bin/keychain
# ls -l /usr/local/bin/kc
lrwxrwxrwx    1 root    root          17 Mar 27 17:44 kc -> keychain
</pre>
Now, we can run the keychain program by typing /usr/local/bin/kc. /usr/local/bin/kc points to the program keychain in the same directory as kc.


= Building for another binary compatible architecture (remote build) =
=== rm ===
Now that we know how to use cp, mv, and ln, it's time to learn how to remove objects from the file system. Normally, this is done with the rm command. To remove files, simply specify them on the command line:
<pre>
$ cd /tmp
$ touch file1 file2
$ ls -l file1 file2
-rw-r--r--    1 root    root            0 Jan  1 16:41 file1
-rw-r--r--    1 root    root            0 Jan  1 16:41 file2
$ rm file1 file2
$ ls -l file1 file2
ls: file1: No such file or directory
ls: file2: No such file or directory
</pre>
Note that under Linux, once a file is rm'ed, it's typically gone forever. For this reason, many junior system administrators will use the -i option when removing files. The -i option tells rm to remove all files in interactive mode -- that is, prompt before removing any file. For example:
<pre>
$ rm -i file1 file2
rm: remove regular empty file `file1'? y
rm: remove regular empty file `file2'? y
</pre>
In the above example, the rm command prompted whether or not the specified files should *really* be deleted. In order for them to be deleted, I had to type "y" and Enter twice. If I had typed "n", the file would not have been removed. Or, if I had done something really wrong, I could have typed Control-C to abort the rm -i command entirely -- all before it is able to do any potential damage to my system.


As written above, [[Metro]] is able to perform '''remote build''' building different architecture stage3 from a binary compatible seeding stage3 (e.g. using a pentium4 stage3 to seed a <tt>Intel Core2 32bits</tt> stage3).
If you are still getting used to the rm command, it can be useful to add the following line to your ~/.bashrc file using your favorite text editor, and then log out and log back in. Then, any time you type rm, the bash shell will convert it automatically to an rm -i command. That way, rm will always work in interactive mode:
<pre>
alias rm="rm -i"
</pre>


In the Metro terminology this is called a '''remote build''' (a stage 3 of a different, but binary compatible, architecture is used as a seed).  
=== rmdir ===
What's not compatible? You can't use a <tt>Sparc</tt> architecture to generate an <tt>x86</tt> or <tt>ARM</tt> based stage and vice-versa. If you use a 32bit stage then you don't want to seed a 64bit build from it. Be sure that you are using a stage from the same architecture that you are trying to seed. Check [http://ftp.osuosl.org/pub/funtoo/funtoo-current/ Funtoo-current FTP Mirror] for a stage that is from the same Architecture that you will be building.
To remove directories, you have two options. You can remove all the objects inside the directory and then use <span style="color:green">rmdir</span> to remove the directory itself:
<pre>
$ mkdir mydir
$ touch mydir/file1
$ rm mydir/file1
$ rmdir mydir
</pre>
This method is commonly referred to as "directory removal for suckers." All real power users and administrators worth their salt use the much more convenient <span style="color:green">rm -rf</span> command, covered next.


{{Note|Often, one build (ie. funtoo-current) can be used as a seed for another build such as funtoo-stable. However, hardened builds require hardened stages as seeds in order for the build to complete successfully.}}
The best way to remove a directory is to use the ''recursive force'' options of the rm command to tell rm to remove the directory you specify, as well as all objects contained in the directory:
<pre>
$ rm -rf mydir
</pre>
Generally, rm -rf is the preferred method of removing a directory tree. Be very careful when using rm -rf, since its power can be used for both good and evil :)


== Step 1: Set up Core_2 32bit repository ==
== Using Wild cards ==


In this example, we're going to use this pentium4 funtoo-current stage3 to seed a new Core_2 32bit funtoo-current build. To get that done, we need to set up the pentium4 build directory as follows:
=== Introducing Wild cards ===
In your day-to-day Linux use, there are many times when you may need to perform a single operation (such as rm) on many file system objects at once. In these situations, it can often be cumbersome to type in many files on the command line:
<pre>
$ rm file1 file2 file3 file4 file5 file6 file7 file8
</pre>
To solve this problem, you can take advantage of Linux' built-in wild card support. This support, also called "globbing" (for historical reasons), allows you to specify multiple files at once by using a wildcard pattern. Bash and other Linux commands will interpret this pattern by looking on disk and finding any files that match it. So, if you had files file1 through file8 in the current working directory, you could remove these files by typing:
<pre>
$ rm file[1-8]
</pre>
Or if you simply wanted to remove all files whose names begin with file as well as any file named file, you could type:
<pre>
$ rm file*
</pre>
The * wildcard matches any character or sequence of characters, or even "no character." Of course, glob wildcards can be used for more than simply removing files, as we'll see in the next panel.


<console>
=== Understanding non-matches ===
# ##i## cd /home/mirror/funtoo/funtoo-current/x86-32bit
If you wanted to list all the file system objects in /etc beginning with g as well as any file called g, you could type:
# ##i##install -d core2_32
<pre>
# ##i##cd core2_32
$ ls -d /etc/g*
# ##i##install -d .control/strategy
/etc/gconf  /etc/ggi  /etc/gimp  /etc/gnome  /etc/gnome-vfs-mime-magic  /etc/gpm  /etc/group  /etc/group-
# ##i##echo remote > .control/strategy/build
</pre>
# ##i##echo stage3 > .control/strategy/seed
Now, what happens if you specify a pattern that doesn't match any file system objects? In the following example, we try to list all the files in /usr/bin that begin with asdf and end with jkl, including potentially the file asdfjkl:
# ##i##install -d .control/remote
<pre>
# ##i##echo funtoo-current > .control/remote/build
$ ls -d /usr/bin/asdf*jkl
# ##i##echo x86-32bit > .control/remote/arch_desc
ls: /usr/bin/asdf*jkl: No such file or directory
# ##i##echo pentium4 > .control/remote/subarch
</pre>
</console>
Here's what happened. Normally, when we specify a pattern, that pattern matches one or more files on the underlying file system, and ''bash replaces the pattern with a space-separated list of all matching objects''. However, when the pattern doesn't produce any matches, ''bash leaves the argument, wild cards and all, as-is''. So, then ls can't find the file /usr/bin/asdf*jkl and it gives us an error. The operative rule here is that ''glob patterns are expanded only if they match objects in the file system''. Otherwise they remain as is and are passed literally to the program you're calling.


The steps we follow are similar to those we performed for a ''local build'' to set up our pentium4 directory for local build. However, note the differences. We didn't download a stage, because we are going to use the pentium4 stage to build a new Core_2 32bit stage. We also didn't create the <tt>.control/version/stage{1,3}</tt> files because Metro will create them for us after it successfully builds a new stage1 and stage3. We are still using a <tt>stage3</tt> seed strategy, but we've set the build strategy to <tt>remote</tt>, which means that we're going to use a seed stage that's not from this particular subdirectory. Where are we going to get it from? The <tt>.control/remote</tt> directory contains this information, and lets Metro know that it should look for its seed stage3 in the <tt>/home/mirror/funtoo/funtoo-current/x86-32bit/pentium4</tt> directory. Which one will it grab? You guessed it -- the most recently built ''stage3'' (since our seed strategy was set to <tt>stage3</tt>) that has the version stamp of <tt>2010-12-24</tt>, as recorded in <tt>/home/mirror/funtoo-current/x86-32bit/pentium4/.control/version/stage</tt>. Now you can see how all those control files come together to direct Metro to do the right thing.
=== Wild card syntax: * and ? ===
Now that we've seen how globbing works, we should look at wild card syntax. You can use special characters for wild card expansion:


{{Note|<code>arch_desc</code> should be set to one of: <code>x86-32bit</code>, <code>x86-64bit</code> or <code>pure64</code> for PC-compatible systems. You must use a 32-bit build as a seed for other 32-bit builds, and a 64-bit build as a seed for other 64-bit builds.}}
<nowiki>*</nowiki> will match zero or more characters. It means "anything can go here, including nothing". Examples:


== Step 2: Building the Core_2 32bit stages ==
* /etc/g* matches all files in /etc that begin with g, or a file called g.
* /tmp/my*1 matches all files in /tmp that begin with my and end with 1, including the file my1.


Now, you could start building your new Core_2 32bit stage1/2/3 (plus openvz and vserver templates) by typing the following:
? matches any single character. Examples:


<console>
* myfile? matches any file whose name consists of myfile followed by a single character
# ##i##/root/metro/scripts/ezbuild.sh funtoo-current core2_32
* /tmp/notes?txt would match both /tmp/notes.txt and /tmp/notes_txt, if they exist
</console>


In that case, the produced stages are placed in the <tt>/home/mirror/funtoo/funtoo-current/x32-bit/core2_32/YYYY-MM-DD</tt> subdirectory.
=== Wild card syntax: [] ===
This wild card is like a ?, but it allows more specificity. To use this wild card, place any characters you'd like to match inside the []. The resultant expression will match a single occurrence of any of these characters. You can also use - to specify a range, and even combine ranges. Examples:


== Step 3: The Next Build ==
* myfile[12] will match myfile1 and myfile2. The wild card will be expanded as long as at least one of these files exists in the current directory.
* [Cc]hange[Ll]og will match Changelog, ChangeLog, changeLog, and changelog. As you can see, using bracket wild cards can be useful for matching variations in capitalization.
* ls /etc/[0-9]* will list all files in /etc that begin with a number.
* ls /tmp/[A-Za-z]* will list all files in /tmp that begin with an upper or lower-case letter.


At this point, you now have a new Core_2 32bit stage3, built using a "remote" pentium4 stage3. Once the first remote build completes successfully, metro will automatically change <code>.control/strategy/build</code> to be <code>local</code> instead of <code>remote</code>, so it will use the most recently-built Core_2 32bit stage3 as a seed for any new Core_2 32bit builds from now on.
The [!] construct is similar to the [] construct, except rather than matching any characters inside the brackets, it'll match any character, as long as it is not listed between the [! and ]. Example:


= Build your own tailored stage3 =
* rm myfile[!9] will remove all files named myfile plus a single character, except for myfile9


Metro can be easily configured for building custom stage3 by including additional packages. Edit the following configuration file <tt>/root/metro/etc/builds/funtoo-current/build.conf</tt>:
=== Wild card caveats ===
{{file|name=funtoo-current/build.conf|body=
Here are some caveats to watch out for when using wild cards. Since bash treats wild card-related characters (?, [, ], and *) specially, you need to take special care when typing in an argument to a command that contains these characters. For example, if you want to create a file that contains the string [fo]*, the following command may not do what you want:
[collect ../../fslayouts/funtoo/layout.conf]
<pre>
$ echo [fo]* > /tmp/mynewfile.txt
</pre>
If the pattern [fo]* matches any files in the current working directory, then you'll find the names of those files inside /tmp/mynewfile.txt rather than a literal [fo]* like you were expecting. The solution? Well, one approach is to surround your characters with single quotes, which tell bash to perform absolutely no wild card expansion on them:
<pre>
$ echo '[fo]*' > /tmp/mynewfile.txt
</pre>
Using this approach, your new file will contain a literal [fo]* as expected. Alternatively, you could use backslash escaping to tell bash that [, ], and * should be treated literally rather than as wild cards:
<pre>
$ echo \[fo\]\* > /tmp/mynewfile.txt
</pre>
Both approaches (single quotes and backslash escaping) have the same effect. Since we're talking about backslash expansion, now would be a good time to mention that in order to specify a literal \, you can either enclose it in single quotes as well, or type \\ instead (it will be expanded to \).
{{fancynote|Double quotes will work similarly to single quotes, but will still allow bash to do some limited expansion. Therefore, single quotes are your best bet when you are truly interested in passing literal text to a command. For more information on wild card expansion, type man 7 glob. For more information on quoting in bash, type man 8 glob and read the section titled QUOTING. If you're planning to take the LPI exams, consider this a homework assignment :)}}


[section release]
== Summary and Resources ==


author: Daniel Robbins <drobbins@funtoo.org>
=== Summary ===
Congratulations; you've reached the end of our review of Linux fundamentals! I hope that it has helped you to firm up your foundational Linux knowledge. The topics you've learned here, including the basics of bash, basic Linux commands, links, and wild cards, have laid the groundwork for our next tutorial on basic administration, in which we'll cover topics like regular expressions, ownership and permissions, user account management, and more.


[section target]
By continuing in this tutorial series, you'll soon be ready to attain your LPIC Level 1 Certification from the Linux Professional Institute. Speaking of LPIC certification, if this is something you're interested in, then we recommend that you study the Resources in the next panel, which have been carefully selected to augment the material covered in this tutorial.


compression: xz
=== Resources ===
Be sure to read the other articles in this series:
*[[Linux Fundamentals, Part 2]]
*[[Linux Fundamentals, Part 3]]
*[[Linux Fundamentals, Part 4]]


[section portage]
In the "Bash by Example" article series, Daniel shows you how to use bash programming constructs to write your own bash scripts. This series (particularly Parts 1 and 2) will be good preparation for the LPIC Level 1 exam:
* [[Bash by Example, Part 1]]: Fundamental programming in the Bourne-again shell
* [[Bash by Example, Part 2]]: More bash programming fundamentals
* [[Bash by Example, Part 3]]: Exploring the ebuild system


FEATURES:
SYNC: $[snapshot/source/remote]
USE:


[section profile]
__NOTOC__
 
[[Category:Linux Core Concepts]]
format: new
[[Category:Articles]]
path: gentoo:funtoo/1.0/linux-gnu
{{ArticleFooter}}
arch: $[:path]/arch/$[target/arch_desc]
build: $[:path]/build/current
flavor: $[:path]/flavor/core
mix-ins:
 
[section version]
 
python: 2.7
 
[section emerge]
 
 
[section snapshot]
 
type: live
compression: xz
 
[section snapshot/source]
 
type: git
branch: funtoo.org
# branch to have checked out for tarball:
branch/tar: origin/master
name: ports-2012
remote: git://github.com/funtoo/ports-2012.git
options: pull
 
[section metro]
 
options:
options/stage: cache/package
target: gentoo
 
[section baselayout]
 
services: sshd
 
[section multi]
 
snapshot: snapshot
 
[section files]
 
motd/trailer: [
 
>>> Send suggestions, improvements, bug reports relating to...
 
>>> This release:                  $[release/author]
>>> Funtoo Linux (general):        Funtoo Linux (http://www.funtoo.org)
>>> Gentoo Linux (general):        Gentoo Linux (http://www.gentoo.org)
]
 
[collect ../../multi-targets/$[multi/mode:zap]]
}}

Revision as of 16:18, January 10, 2015

   Support Funtoo!
Get an awesome Funtoo container and support Funtoo! See Funtoo Containers for more information.

Antes de Iinciar

About this tutorial

Bem vindo ao "Linux fundamentals," o primeiro de quatro tutoriais desenvolvido para lhe preparar para o exame da Linux Professional Institute's 101 (LPI 101). Nesse tutorial, vamos lhe introduzir ao bash (o shell padrão do Linux), lhe mostrar como tirar vantagem dos comando padrões do Linux como like ls, cp, e mv, explicar inodes e hard links e links simbólicos, e muito mais. Ao final desse tutorial, você terá sólida base no Linux fundamentals e estará até mesmo pronto para começar a aprender algumas tarefas básicas de administração do sistema Linux. Ao final dessa série de tutoriais (oito ao todo), você terá conhecimento que você precisa para se tornar um administrador Linux e estará pronto para realizar uma certificação LPIC nível 1 da Linux Professional Institute se você escolher assim.

Esse tutorial particular (Parte 1) é ideal para aqueles que são novos no Linux, ou para aqueles que querem rever ou melhorar seus entendimentos dos conceitos fundamentais do Linux como copiar e mover arquivos, criar symbolic e hard links, e utilizar comandos de processamento de texto padrão do Linux juntamente com pipelines e redirecionamento. Ao longo do caminho, compartilharemos um monte de sugestões, dicas, e truques para manter o tutorial robusto e prático, mesmo para aqueles com uma bom montante de experiencia anterior em Linux. Para iniciantes, muito desse será novo, mas usuários de Linux mais experientes podem achar esse tutorial ser um ótimo jeito de circundar suas habilidades fundamentais em Linux.

For those who have taken the release 1 version of this tutorial for reasons other than LPI exam preparation, you probably don't need to take this one. However, if you do plan to take the exams, you should strongly consider reading this revised tutorial.

Introducing bash

The shell

If you've used a Linux system, you know that when you log in, you are greeted by a prompt that looks something like this:

$

The particular prompt that you see may look quite different. It may contain your systems host name, the name of the current working directory, or both. But regardless of what your prompt looks like, there's one thing that's certain. The program that printed that prompt is called a "shell," and it's very likely that your particular shell is a program called bash.

Are you running bash?

You can check to see if you're running bash by typing:

$ echo $SHELL
/bin/bash

If the above line gave you an error or didn't respond similarly to our example, then you may be running a shell other than bash. In that case, most of this tutorial should still apply, but it would be advantageous for you to switch to bash for the sake of preparing for the 101 exam.

About bash

Bash, an acronym for "Bourne-again shell," is the default shell on most Linux systems. The shell's job is to obey your commands so that you can interact with your Linux system. When you're finished entering commands, you may instruct the shell to exit or logout, at which point you'll be returned to a login prompt.

By the way, you can also log out by pressing control-D at the bash prompt.

Using "cd"

As you've probably found, staring at your bash prompt isn't the most exciting thing in the world. So, let's start using bash to navigate around our file system. At the prompt, type the following (without the $):

$ cd /

We've just told bash that you want to work in /, also known as the root directory; all the directories on the system form a tree, and / is considered the top of this tree, or the root. cd sets the directory where you are currently working, also known as the "current working directory."

Paths

To see bash's current working directory, you can type:

$ pwd
/

In the above example, the / argument to cd is called a path. It tells cd where we want to go. In particular, the / argument is an absolute path, meaning that it specifies a location relative to the root of the file system tree.

Absolute paths

Here are some other absolute paths:

/dev
/usr
/usr/bin
/usr/local/bin

As you can see, the one thing that all absolute paths have in common is that they begin with /. With a path of /usr/local/bin, we're telling cd to enter the / directory, then the usr directory under that, and then local and bin. Absolute paths are always evaluated by starting at / first.

Relative paths

The other kind of path is called a relative path. Bash, cd, and other commands always interpret these paths relative to the current directory. Relative paths never begin with a /. So, if we're in /usr:

$ cd /usr

Then, we can use a relative path to change to the /usr/local/bin directory:

$ cd local/bin
$ pwd
/usr/local/bin

Using ..

Relative paths may also contain one or more .. directories. The .. directory is a special directory that points to the parent directory. So, continuing from the example above:

$ pwd
/usr/local/bin
$ cd ..
$ pwd
/usr/local

As you can see, our current directory is now /usr/local. We were able to go "backwards" one directory, relative to the current directory that we were in.

In addition, we can also add .. to an existing relative path, allowing us to go into a directory that's alongside one we are already in, for example:

$ pwd
/usr/local
$ cd ../share
$ pwd
/usr/share

Relative path examples

Relative paths can get quite complex. Here are a few examples, all without the resultant target directory displayed. Try to figure out where you'll end up after typing these commands:

$ cd /bin
$ cd ../usr/share/zoneinfo


$ cd /usr/X11R6/bin
$ cd ../lib/X11


$ cd /usr/bin
$ cd ../bin/../bin

Now, try them out and see if you got them right :)

Understanding "."

Before we finish our coverage of cd, there are a few more things I need to mention. First, there is another special directory called ., which means "the current directory". While this directory isn't used with the cd command, it's often used to execute some program in the current directory, as follows:

$ ./myprog

In the above example, the myprog executable residing in the current working directory will be executed.

cd and the home directory

If we wanted to change to our home directory, we could type:

$ cd

With no arguments, cd will change to your home directory, which is /root for the superuser and typically /home/username for a regular user. But what if we want to specify a file in our home directory? Maybe we want to pass a file argument to the myprog command. If the file lives in our home directory, we can type:

$ ./myprog /home/drobbins/myfile.txt

However, using an absolute path like that isn't always convenient. Thankfully, we can use the ~ (tilde) character to do the same thing:

$ ./myprog ~/myfile.txt

Other users' home directories

Bash will expand a lone ~ to point to your home directory, but you can also use it to point to other users' home directories. For example, if we wanted to refer to a file called fredsfile.txt in Fred's home directory, we could type:

$ ./myprog ~fred/fredsfile.txt

Using Linux Commands

Introducing ls

Now, we'll take a quick look at the ls command. Very likely, you're already familiar with ls and know that typing it by itself will list the contents of the current working directory:

$ cd /usr
$ ls
X11R6      doc         i686-pc-linux-gnu  lib      man          sbin   ssl
bin        gentoo-x86  include            libexec  portage      share  tmp
distfiles  i686-linux  info               local    portage.old  src

By specifying the -a option, you can see all of the files in a directory, including hidden files: those that begin with .. As you can see in the following example, ls -a reveals the . and .. special directory links:

$ ls -a
.      bin        gentoo-x86         include  libexec  portage      share  tmp
..     distfiles  i686-linux         info     local    portage.old  src
X11R6  doc        i686-pc-linux-gnu  lib      man      sbin         ssl

Long directory listings

You can also specify one or more files or directories on the ls command line. If you specify a file, ls will show that file only. If you specify a directory, ls will show the contents of the directory. The -l option comes in very handy when you need to view permissions, ownership, modification time, and size information in your directory listing.

In the following example, we use the -l option to display a full listing of my /usr directory.

$ ls -l /usr
drwxr-xr-x    7 root     root          168 Nov 24 14:02 X11R6
drwxr-xr-x    2 root     root        14576 Dec 27 08:56 bin
drwxr-xr-x    2 root     root         8856 Dec 26 12:47 distfiles
lrwxrwxrwx    1 root     root            9 Dec 22 20:57 doc -> share/doc
drwxr-xr-x   62 root     root         1856 Dec 27 15:54 gentoo-x86
drwxr-xr-x    4 root     root          152 Dec 12 23:10 i686-linux
drwxr-xr-x    4 root     root           96 Nov 24 13:17 i686-pc-linux-gnu
drwxr-xr-x   54 root     root         5992 Dec 24 22:30 include
lrwxrwxrwx    1 root     root           10 Dec 22 20:57 info -> share/info
drwxr-xr-x   28 root     root        13552 Dec 26 00:31 lib
drwxr-xr-x    3 root     root           72 Nov 25 00:34 libexec
drwxr-xr-x    8 root     root          240 Dec 22 20:57 local
lrwxrwxrwx    1 root     root            9 Dec 22 20:57 man -> share/man
lrwxrwxrwx    1 root     root           11 Dec  8 07:59 portage -> gentoo-x86/
drwxr-xr-x   60 root     root         1864 Dec  8 07:55 portage.old
drwxr-xr-x    3 root     root         3096 Dec 22 20:57 sbin
drwxr-xr-x   46 root     root         1144 Dec 24 15:32 share
drwxr-xr-x    8 root     root          328 Dec 26 00:07 src
drwxr-xr-x    6 root     root          176 Nov 24 14:25 ssl
lrwxrwxrwx    1 root     root           10 Dec 22 20:57 tmp -> ../var/tmp

The first column displays permissions information for each item in the listing. I'll explain how to interpret this information in a bit. The next column lists the number of links to each file system object, which we'll gloss over now but return to later. The third and fourth columns list the owner and group, respectively. The fifth column lists the object size. The sixth column is the "last modified" time or "mtime" of the object. The last column is the object's name. If the file is a symbolic link, you'll see a trailing -> and the path to which the symbolic link points.

Looking at directories

Sometimes, you'll want to look at a directory, rather than inside it. For these situations, you can specify the -d option, which will tell ls to look at any directories that it would normally look inside:

$ ls -dl /usr /usr/bin /usr/X11R6/bin ../share
drwxr-xr-x    4 root     root           96 Dec 18 18:17 ../share
drwxr-xr-x   17 root     root          576 Dec 24 09:03 /usr
drwxr-xr-x    2 root     root         3192 Dec 26 12:52 /usr/X11R6/bin
drwxr-xr-x    2 root     root        14576 Dec 27 08:56 /usr/bin

Recursive and inode listings

So you can use -d to look at a directory, but you can also use -R to do the opposite: not just look inside a directory, but recursively look inside all the files and directories inside that directory! We won't include any example output for this option (since it's generally voluminous), but you may want to try a few ls -R and ls -Rl commands to get a feel for how this works.

Finally, the -i ls option can be used to display the inode numbers of the file system objects in the listing:

$ ls -i /usr
   1409 X11R6        314258 i686-linux           43090 libexec        13394 sbin
   1417 bin            1513 i686-pc-linux-gnu     5120 local          13408 share
   8316 distfiles      1517 include                776 man            23779 src
     43 doc            1386 info                 93892 portage        36737 ssl
  70744 gentoo-x86     1585 lib                   5132 portage.old      784 tmp

Understanding inodes

Every object on a file system is assigned a unique index, called an inode number. This might seem trivial, but understanding inodes is essential to understanding many file system operations. For example, consider the . and .. links that appear in every directory. To fully understand what a .. directory actually is, we'll first take a look at /usr/local's inode number:

$ ls -id /usr/local
   5120 /usr/local

The /usr/local directory has an inode number of 5120. Now, let's take a look at the inode number of /usr/local/bin/..:

$ ls -id /usr/local/bin/..
   5120 /usr/local/bin/..

As you can see, /usr/local/bin/.. has the same inode number as /usr/local! Here's how we can come to grips with this shocking revelation. In the past, we've considered /usr/local to be the directory itself. Now, we discover that inode 5120 is in fact the directory, and we have found two directory entries (called "links") that point to this inode. Both /usr/local and /usr/local/bin/.. are links to inode 5120. Although inode 5120 only exists in one place on disk, multiple things link to it. Inode 5120 is the actual entry on disk.

In fact, we can see the total number of times that inode 5120 is referenced by using the
ls -dl
command:
$ ls -dl /usr/local
drwxr-xr-x    8 root     root          240 Dec 22 20:57 /usr/local

If we take a look at the second column from the left, we see that the directory /usr/local (inode 5120) is referenced eight times. On my system, here are the various paths that reference this inode:

/usr/local
/usr/local/.
/usr/local/bin/..
/usr/local/games/..
/usr/local/lib/..
/usr/local/sbin/..
/usr/local/share/..
/usr/local/src/..

mkdir

Let's take a quick look at the mkdir command, which can be used to create new directories. The following example creates three new directories, tic, tac, and toe, all under /tmp:

$ cd /tmp
$ mkdir tic tac toe

By default, the mkdir command doesn't create parent directories for you; the entire path up to the next-to-last element needs to exist. So, if you want to create the directories won/der/ful, you'd need to issue three separate mkdir commands:

$ mkdir won/der/ful
mkdir: cannot create directory `won/der/ful': No such file or directory
$ mkdir won
$ mkdir won/der
$ mkdir won/der/ful

However, mkdir has a handy -p option that tells mkdir to create any missing parent directories, as you can see here:

$ mkdir -p easy/as/pie

All in all, pretty straightforward. To learn more about the mkdir command, type man mkdir to read the manual page. This will work for nearly all commands covered here (for example, man ls), except for cd, which is built-in to bash.

touch

Now, we're going to take a quick look at the cp and mv commands, used to copy, rename, and move files and directories. To begin this overview, we'll first use the touch command to create a file in /tmp:

$ cd /tmp
$ touch copyme

The touch command updates the "mtime" of a file if it exists (recall the sixth column in ls -l output). If the file doesn't exist, then a new, empty file will be created. You should now have a /tmp/copyme file with a size of zero.

echo

Now that the file exists, let's add some data to the file. We can do this using the echo command, which takes its arguments and prints them to standard output. First, the echo command by itself:

$ echo "firstfile"
firstfile

Now, the same echo command with output redirection:

$ echo "firstfile" > copyme

The greater-than sign tells the shell to write echo's output to a file called copyme. This file will be created if it doesn't exist, and will be overwritten if it does exist. By typing ls -l, we can see that the copyme file is 10 bytes long, since it contains the word firstfile and the newline character:

$ ls -l copyme
-rw-r--r--    1 root     root           10 Dec 28 14:13 copyme

cat and cp

To display the contents of the file on the terminal, use the cat command:

$ cat copyme
firstfile

Now, we can use a basic invocation of the cp command to create a copiedme file from the original copyme file:

$ cp copyme copiedme

Upon investigation, we find that they are truly separate files; their inode numbers are different:

$ ls -i copyme copiedme
  648284 copiedme   650704 copyme

mv

Now, let's use the mv command to rename "copiedme" to "movedme". The inode number will remain the same; however, the filename that points to the inode will change.

$ mv copiedme movedme
$ ls -i movedme
  648284 movedme

A moved file's inode number will remain the same as long as the destination file resides on the same file system as the source file. We'll take a closer look at file systems in Linux Fundamentals, Part 3 of this tutorial series.

While we're talking about mv, let's look at another way to use this command. mv, in addition to allowing us to rename files, also allows us to move one or more files to another location in the directory hierarchy. For example, to move /var/tmp/myfile.txt to /home/drobbins (which happens to be my home directory,) I could type:

$ mv /var/tmp/myfile.txt /home/drobbins

After typing this command, myfile.txt will be moved to /home/drobbins/myfile.txt. And if /home/drobbins is on a different file system than /var/tmp, the mv command will handle the copying of myfile.txt to the new file system and erasing it from the old file system. As you might guess, when myfile.txt is moved between file systems, the myfile.txt at the new location will have a new inode number. This is because every file system has its own independent set of inode numbers.

We can also use the mv command to move multiple files to a single destination directory. For example, to move myfile1.txt and myarticle3.txt to /home/drobbins, I could type:

$ mv /var/tmp/myfile1.txt /var/tmp/myarticle3.txt /home/drobbins

Creating Links and Removing Files

Hard links

We've mentioned the term "link" when referring to the relationship between directory entries (the "names" we type) and inodes (the index numbers on the underlying file system that we can usually ignore.) There are actually two kinds of links available on Linux. The kind we've discussed so far are called hard links. A given inode can have any number of hard links, and the inode will persist on the file system until all the hard links disappear. When the last hard link disappears and no program is holding the file open, Linux will delete the file automatically. New hard links can be created using the ln command:

$ cd /tmp
$ touch firstlink
$ ln firstlink secondlink
$ ls -i firstlink secondlink
  15782 firstlink    15782 secondlink

As you can see, hard links work on the inode level to point to a particular file. On Linux systems, hard links have several limitations. For one, you can only make hard links to files, not directories. That's right; even though . and .. are system-created hard links to directories, you (even as the "root" user) aren't allowed to create any of your own. The second limitation of hard links is that they can't span file systems; which would be the case if the file systems are on separate disk partitions. This means that you can't create a link from /usr/bin/bash to /bin/bash if your / and /usr directories exist on separate disk partitions.

Symbolic links

In practice, symbolic links (or symlinks) are used more often than hard links. Symlinks are a special file type where the link refers to another file by name, rather than directly to the inode. Symlinks do not prevent a file from being deleted; if the target file disappears, then the symlink will just be unusable, or broken.

A symbolic link can be created by passing the -s option to ln.

$ ln -s secondlink thirdlink
$ ls -l firstlink secondlink thirdlink
-rw-rw-r--    2 agriffis agriffis        0 Dec 31 19:08 firstlink
-rw-rw-r--    2 agriffis agriffis        0 Dec 31 19:08 secondlink
lrwxrwxrwx    1 agriffis agriffis       10 Dec 31 19:39 thirdlink -> secondlink

Symbolic links can be distinguished in ls -l output from normal files in three ways. First, notice that the first column contains an l character to signify the symbolic link. Second, the size of the symbolic link is the number of characters in the target (secondlink, in this case). Third, the last column of the output displays the target filename preceded by a cute little ->.

Symlinks in-depth

Symbolic links are generally more flexible than hard links. You can create a symbolic link to any type of file system object, including directories. And because the implementation of symbolic links is based on paths (not inodes), it's perfectly fine to create a symbolic link that points to an object on another physical file system; that is, a different disk partition. However, this fact can also make symbolic links tricky to understand.

Consider a situation where we want to create a link in /tmp that points to /usr/local/bin. Should we type this:

$ ln -s /usr/local/bin bin1
$ ls -l bin1
lrwxrwxrwx    1 root     root           14 Jan  1 15:42 bin1 -> /usr/local/bin

Or alternatively:

$ ln -s ../usr/local/bin bin2
$ ls -l bin2
lrwxrwxrwx    1 root     root           16 Jan  1 15:43 bin2 -> ../usr/local/bin

As you can see, both symbolic links point to the same directory. However, if our second symbolic link is ever moved to another directory, it will be "broken" because of the relative path:

$ ls -l bin2
lrwxrwxrwx    1 root     root           16 Jan  1 15:43 bin2 -> ../usr/local/bin
$ mkdir mynewdir
$ mv bin2 mynewdir
$ cd mynewdir
$ cd bin2
bash: cd: bin2: No such file or directory

Because the directory /tmp/usr/local/bin doesn't exist, we can no longer change directories into bin2; in other words, bin2 is now broken.

For this reason, it is sometimes a good idea to avoid creating symbolic links with relative path information. However, there are many cases where relative symbolic links come in handy. Consider an example where you want to create an alternate name for a program in /usr/bin:

# ls -l /usr/bin/keychain 
-rwxr-xr-x    1 root     root        10150 Dec 12 20:09 /usr/bin/keychain

As the root user, you may want to create an alternate name for "keychain", such as "kc". In this example, we have root access, as evidenced by our bash prompt changing to "#". We need root access because normal users aren't able to create files in /usr/bin. As root, we could create an alternate name for keychain as follows:

# cd /usr/bin
# ln -s /usr/bin/keychain kc
# ls -l keychain
-rwxr-xr-x    1 root     root        10150 Dec 12 20:09 /usr/bin/keychain
# ls -l kc       
lrwxrwxrwx    1 root     root           17 Mar 27 17:44 kc -> /usr/bin/keychain

In this example, we created a symbolic link called kc that points to the file /usr/bin/keychain.

While this solution will work, it will create problems if we decide that we want to move both files, /usr/bin/keychain and /usr/bin/kc to /usr/local/bin:

# mv /usr/bin/keychain /usr/bin/kc /usr/local/bin
# ls -l /usr/local/bin/keychain
-rwxr-xr-x    1 root     root        10150 Dec 12 20:09 /usr/local/bin/keychain
# ls -l /usr/local/bin/kc
lrwxrwxrwx    1 root     root           17 Mar 27 17:44 kc -> /usr/bin/keychain

Because we used an absolute path in our symbolic link, our kc symlink is still pointing to /usr/bin/keychain, which no longer exists since we moved /usr/bin/keychain to /usr/local/bin.

That means that kc is now a broken symlink. Both relative and absolute paths in symbolic links have their merits, and you should use a type of path that's appropriate for your particular application. Often, either a relative or absolute path will work just fine. The following example would have worked even after both files were moved:

# cd /usr/bin
# ln -s keychain kc
# ls -l kc
lrwxrwxrwx    1 root     root            8 Jan  5 12:40 kc -> keychain
# mv keychain kc /usr/local/bin
# ls -l /usr/local/bin/keychain
-rwxr-xr-x    1 root     root        10150 Dec 12 20:09 /usr/local/bin/keychain
# ls -l /usr/local/bin/kc
lrwxrwxrwx    1 root     root           17 Mar 27 17:44 kc -> keychain

Now, we can run the keychain program by typing /usr/local/bin/kc. /usr/local/bin/kc points to the program keychain in the same directory as kc.

rm

Now that we know how to use cp, mv, and ln, it's time to learn how to remove objects from the file system. Normally, this is done with the rm command. To remove files, simply specify them on the command line:

$ cd /tmp
$ touch file1 file2
$ ls -l file1 file2
-rw-r--r--    1 root     root            0 Jan  1 16:41 file1
-rw-r--r--    1 root     root            0 Jan  1 16:41 file2
$ rm file1 file2
$ ls -l file1 file2
ls: file1: No such file or directory
ls: file2: No such file or directory

Note that under Linux, once a file is rm'ed, it's typically gone forever. For this reason, many junior system administrators will use the -i option when removing files. The -i option tells rm to remove all files in interactive mode -- that is, prompt before removing any file. For example:

$ rm -i file1 file2
rm: remove regular empty file `file1'? y
rm: remove regular empty file `file2'? y

In the above example, the rm command prompted whether or not the specified files should *really* be deleted. In order for them to be deleted, I had to type "y" and Enter twice. If I had typed "n", the file would not have been removed. Or, if I had done something really wrong, I could have typed Control-C to abort the rm -i command entirely -- all before it is able to do any potential damage to my system.

If you are still getting used to the rm command, it can be useful to add the following line to your ~/.bashrc file using your favorite text editor, and then log out and log back in. Then, any time you type rm, the bash shell will convert it automatically to an rm -i command. That way, rm will always work in interactive mode:

alias rm="rm -i"

rmdir

To remove directories, you have two options. You can remove all the objects inside the directory and then use rmdir to remove the directory itself:

$ mkdir mydir
$ touch mydir/file1
$ rm mydir/file1
$ rmdir mydir

This method is commonly referred to as "directory removal for suckers." All real power users and administrators worth their salt use the much more convenient rm -rf command, covered next.

The best way to remove a directory is to use the recursive force options of the rm command to tell rm to remove the directory you specify, as well as all objects contained in the directory:

$ rm -rf mydir

Generally, rm -rf is the preferred method of removing a directory tree. Be very careful when using rm -rf, since its power can be used for both good and evil :)

Using Wild cards

Introducing Wild cards

In your day-to-day Linux use, there are many times when you may need to perform a single operation (such as rm) on many file system objects at once. In these situations, it can often be cumbersome to type in many files on the command line:

$ rm file1 file2 file3 file4 file5 file6 file7 file8

To solve this problem, you can take advantage of Linux' built-in wild card support. This support, also called "globbing" (for historical reasons), allows you to specify multiple files at once by using a wildcard pattern. Bash and other Linux commands will interpret this pattern by looking on disk and finding any files that match it. So, if you had files file1 through file8 in the current working directory, you could remove these files by typing:

$ rm file[1-8]

Or if you simply wanted to remove all files whose names begin with file as well as any file named file, you could type:

$ rm file*

The * wildcard matches any character or sequence of characters, or even "no character." Of course, glob wildcards can be used for more than simply removing files, as we'll see in the next panel.

Understanding non-matches

If you wanted to list all the file system objects in /etc beginning with g as well as any file called g, you could type:

$ ls -d /etc/g*
/etc/gconf  /etc/ggi  /etc/gimp  /etc/gnome  /etc/gnome-vfs-mime-magic  /etc/gpm  /etc/group  /etc/group-

Now, what happens if you specify a pattern that doesn't match any file system objects? In the following example, we try to list all the files in /usr/bin that begin with asdf and end with jkl, including potentially the file asdfjkl:

$ ls -d /usr/bin/asdf*jkl
ls: /usr/bin/asdf*jkl: No such file or directory

Here's what happened. Normally, when we specify a pattern, that pattern matches one or more files on the underlying file system, and bash replaces the pattern with a space-separated list of all matching objects. However, when the pattern doesn't produce any matches, bash leaves the argument, wild cards and all, as-is. So, then ls can't find the file /usr/bin/asdf*jkl and it gives us an error. The operative rule here is that glob patterns are expanded only if they match objects in the file system. Otherwise they remain as is and are passed literally to the program you're calling.

Wild card syntax: * and ?

Now that we've seen how globbing works, we should look at wild card syntax. You can use special characters for wild card expansion:

* will match zero or more characters. It means "anything can go here, including nothing". Examples:

  • /etc/g* matches all files in /etc that begin with g, or a file called g.
  • /tmp/my*1 matches all files in /tmp that begin with my and end with 1, including the file my1.

? matches any single character. Examples:

  • myfile? matches any file whose name consists of myfile followed by a single character
  • /tmp/notes?txt would match both /tmp/notes.txt and /tmp/notes_txt, if they exist

Wild card syntax: []

This wild card is like a ?, but it allows more specificity. To use this wild card, place any characters you'd like to match inside the []. The resultant expression will match a single occurrence of any of these characters. You can also use - to specify a range, and even combine ranges. Examples:

  • myfile[12] will match myfile1 and myfile2. The wild card will be expanded as long as at least one of these files exists in the current directory.
  • [Cc]hange[Ll]og will match Changelog, ChangeLog, changeLog, and changelog. As you can see, using bracket wild cards can be useful for matching variations in capitalization.
  • ls /etc/[0-9]* will list all files in /etc that begin with a number.
  • ls /tmp/[A-Za-z]* will list all files in /tmp that begin with an upper or lower-case letter.

The [!] construct is similar to the [] construct, except rather than matching any characters inside the brackets, it'll match any character, as long as it is not listed between the [! and ]. Example:

  • rm myfile[!9] will remove all files named myfile plus a single character, except for myfile9

Wild card caveats

Here are some caveats to watch out for when using wild cards. Since bash treats wild card-related characters (?, [, ], and *) specially, you need to take special care when typing in an argument to a command that contains these characters. For example, if you want to create a file that contains the string [fo]*, the following command may not do what you want:

$ echo [fo]* > /tmp/mynewfile.txt

If the pattern [fo]* matches any files in the current working directory, then you'll find the names of those files inside /tmp/mynewfile.txt rather than a literal [fo]* like you were expecting. The solution? Well, one approach is to surround your characters with single quotes, which tell bash to perform absolutely no wild card expansion on them:

$ echo '[fo]*' > /tmp/mynewfile.txt

Using this approach, your new file will contain a literal [fo]* as expected. Alternatively, you could use backslash escaping to tell bash that [, ], and * should be treated literally rather than as wild cards:

$ echo \[fo\]\* > /tmp/mynewfile.txt

Both approaches (single quotes and backslash escaping) have the same effect. Since we're talking about backslash expansion, now would be a good time to mention that in order to specify a literal \, you can either enclose it in single quotes as well, or type \\ instead (it will be expanded to \).

   Note

Double quotes will work similarly to single quotes, but will still allow bash to do some limited expansion. Therefore, single quotes are your best bet when you are truly interested in passing literal text to a command. For more information on wild card expansion, type man 7 glob. For more information on quoting in bash, type man 8 glob and read the section titled QUOTING. If you're planning to take the LPI exams, consider this a homework assignment :)

Summary and Resources

Summary

Congratulations; you've reached the end of our review of Linux fundamentals! I hope that it has helped you to firm up your foundational Linux knowledge. The topics you've learned here, including the basics of bash, basic Linux commands, links, and wild cards, have laid the groundwork for our next tutorial on basic administration, in which we'll cover topics like regular expressions, ownership and permissions, user account management, and more.

By continuing in this tutorial series, you'll soon be ready to attain your LPIC Level 1 Certification from the Linux Professional Institute. Speaking of LPIC certification, if this is something you're interested in, then we recommend that you study the Resources in the next panel, which have been carefully selected to augment the material covered in this tutorial.

Resources

Be sure to read the other articles in this series:

In the "Bash by Example" article series, Daniel shows you how to use bash programming constructs to write your own bash scripts. This series (particularly Parts 1 and 2) will be good preparation for the LPIC Level 1 exam:

   Tip

Read the next article in this series: Linux Fundamentals, Part 2

   Note

Browse all our available articles below. Use the search field to search for topics and keywords in real-time.

Article Subtitle
Article Subtitle
Awk by Example, Part 1 An intro to the great language with the strange name
Awk by Example, Part 2 Records, loops, and arrays
Awk by Example, Part 3 String functions and ... checkbooks?
Bash by Example, Part 1 Fundamental programming in the Bourne again shell (bash)
Bash by Example, Part 2 More bash programming fundamentals
Bash by Example, Part 3 Exploring the ebuild system
BTRFS Fun
Funtoo Filesystem Guide, Part 1 Journaling and ReiserFS
Funtoo Filesystem Guide, Part 2 Using ReiserFS and Linux
Funtoo Filesystem Guide, Part 3 Tmpfs and Bind Mounts
Funtoo Filesystem Guide, Part 4 Introducing Ext3
Funtoo Filesystem Guide, Part 5 Ext3 in Action
GUID Booting Guide
Learning Linux LVM, Part 1 Storage management magic with Logical Volume Management
Learning Linux LVM, Part 2 The cvs.gentoo.org upgrade
Libvirt
Linux Fundamentals, Part 1
Linux Fundamentals, Part 2
Linux Fundamentals, Part 3
Linux Fundamentals, Part 4
LVM Fun
Making the Distribution, Part 1
Making the Distribution, Part 2
Making the Distribution, Part 3
Maximum Swappage Getting the most out of swap
On screen annotation Write on top of apps on your screen
OpenSSH Key Management, Part 1 Understanding RSA/DSA Authentication
OpenSSH Key Management, Part 2 Introducing ssh-agent and keychain
OpenSSH Key Management, Part 3 Agent Forwarding
Partition Planning Tips Keeping things organized on disk
Partitioning in Action, Part 1 Moving /home
Partitioning in Action, Part 2 Consolidating data
POSIX Threads Explained, Part 1 A simple and nimble tool for memory sharing
POSIX Threads Explained, Part 2
POSIX Threads Explained, Part 3 Improve efficiency with condition variables
Sed by Example, Part 1
Sed by Example, Part 2
Sed by Example, Part 3
Successful booting with UUID Guide to use UUID for consistent booting.
The Gentoo.org Redesign, Part 1 A site reborn
The Gentoo.org Redesign, Part 2 The Documentation System
The Gentoo.org Redesign, Part 3 The New Main Pages
The Gentoo.org Redesign, Part 4 The Final Touch of XML
Traffic Control
Windows 10 Virtualization with KVM