Christopher Negus - Linux Bible

Здесь есть возможность читать онлайн «Christopher Negus - Linux Bible» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Linux Bible: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Linux Bible»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

The industry favorite Linux guide
Linux Bible, 10th Edition This useful guide assumes a base of little or no Linux knowledge, and takes you step by step through what you need to know to get the job done.
Get Linux up and running quickly Master basic operations and tackle more advanced tasks Get up to date on the recent changes to Linux server system management Bring Linux to the cloud using Openstack and Cloudforms Simplified Linux administration through the Cockpit Web Interface Automated Linux Deployment with Ansible Learn to navigate Linux with Amazon (AWS), Google (GCE), and Microsofr Azure Cloud services 
 is the one resource you need, and provides the hands-on training that gets you on track in a flash.

Linux Bible — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Linux Bible», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Using variables is a great way to get information that can change from computer to computer or from day to day. The following example sets the output of the uname -ncommand to the MACHINEvariable. Then I use parentheses to set NUM_FILESto the number of files in the current directory by piping ( |) the output of the lscommand to the word count command ( wc -l):

MACHINE=`uname -n` NUM_FILES=$(/bin/ls | wc -l)

Variables can also contain the value of other variables. This is useful when you have to preserve a value that will change so that you can use it later in the script. Here, BALANCEis set to the value of the CurBalancevariable:

BALANCE="$CurBalance"

NOTE

When assigning variables, use only the variable name (for example, BALANCE). When you reference a variable, meaning that you want the value of the variable, precede it with a dollar sign (as in $CurBalance). The result of the latter is that you get the value of the variable, not the variable name itself.

Special shell positional parameters

There are special variables that the shell assigns for you. One set of commonly used variables is called positional parameters or command-line arguments , and it is referenced as $0, $1, $2, $3…$ n . $0 is special, and it is assigned the name used to invoke your script; the others are assigned the values of the parameters passed on the command line in the order they appeared. For instance, let's say that you had a shell script named myscriptwhich contained the following:

#!/bin/bash # Script to echo out command-line arguments echo "The first argument is $1, the second is $2." echo "The command itself is called $0." echo "There are $# parameters on your command line" echo "Here are all the arguments: $@"

Assuming that the script is executable and located in a directory in your $PATH, the following shows what would happen if you ran that command with fooand baras arguments:

$ chmod 755 /home/chris/bin/myscript $ myscript foo bar The first argument is foo, the second is bar. The command itself is called /home/chris/bin/myscript. There are 2 parameters on your command line Here are all the arguments: foo bar

As you can see, the positional parameter $0is the full path or relative path to myscript, $1is foo, and $2is bar.

Another variable, $#, tells you how many parameters your script was given. In the example, $#would be 2. The $@variable holds all of the arguments entered at the command line. Another particularly useful special shell variable is $?, which receives the exit status of the last command executed. Typically, a value of zero means that the command exited successfully, and anything other than zero indicates an error of some kind. For a complete list of special shell variables, refer to the bashman page.

Reading in parameters

Using the readcommand, you can prompt the user for information and store that information to use later in your script. Here's an example of a script that uses the readcommand:

#!/bin/bash read -p "Type in an adjective, noun and verb (past tense): " adj1 noun1 verb1 echo "He sighed and $verb1 to the elixir. Then he ate the $adj1 $noun1."

In this script, after the script prompts for an adjective, noun, and verb, the user is expected to enter words that are then assigned to the adj1, noun1, and verb1variables. Those three variables are then included in a silly sentence, which is displayed on the screen. If the script were called sillyscript, here's an example of how it might run:

$ chmod 755 /home/chris/bin/sillyscript $ sillyscript Type in an adjective, noun and verb (past tense): hairy football danced He sighed and danced to the elixir. Then he ate the hairy football.

Parameter expansion in bash

As mentioned earlier, if you want the value of a variable, you precede it with a $(for example, $CITY). This is really just shorthand for the notation ${CITY}; curly braces are used when the value of the parameter needs to be placed next to other text without a space. Bash has special rules that allow you to expand the value of a variable in different ways. Going into all of the rules is probably overkill for a quick introduction to shell scripts, but the following list presents some common constructs you're likely to see in bash scripts that you find on your Linux system.

${var:-value}: If variable is unset or empty, expand this to value.

${var#pattern}: Chop the shortest match for pattern from the front of var's value.

${var##pattern}: Chop the longest match for pattern from the front of var's value.

${var%pattern}: Chop the shortest match for pattern from the end of var's value.

${var%%pattern}: Chop the longest match for pattern from the end of var's value.

Try typing the following commands from a shell to test how parameter expansion works:

$ THIS="Example" $ THIS=${THIS:-"Not Set"} $ THAT=${THAT:-"Not Set"} $ echo $THIS Example $ echo $THAT Not Set

In the examples here, the THISvariable is initially set to the word Example. In the next two lines, the THISand THATvariables are set to their current values or to Not Set, if they are not currently set. Notice that because I just set THISto the string Example, when I echo the value of THISit appears as Example. However, because THATwas not set, it appears as Not Set.

NOTE

For the rest of this section, I show how variables and commands may appear in a shell script. To try out any of those examples, however, you can simply type them into a shell, as shown in the previous example.

In the following example, MYFILENAMEis set to /home/digby/myfile.txt. Next, the FILEvariable is set to myfile.txtand DIRis set to /home/digby. In the NAMEvariable, the filename is cut down simply to myfile; then, in the EXTENSIONvariable, the file extension is set to txt. (To try these out, you can type them at a shell prompt as in the previous example and echo the value of each variable to see how it is set.) Type the code on the left. The material on the right side describes the action.

MYFILENAME=/home/digby/myfile.txt: Sets the value of MYFILENAME

FILE=${MYFILENAME##*/}: FILE becomes myfile.txt

DIR=${MYFILENAME%/*}: DIR becomes /home/digby

NAME=${FILE%.*}: NAME becomes myfile

EXTENSION=${FILE##*.}: EXTENSION becomes txt

Performing arithmetic in shell scripts

Bash uses untyped variables , meaning it normally treats variables as strings of text, but you can change them on the fly if you want it to.

Bash uses untyped variables , meaning that you are not required to specify whether a variable is text or numbers. It normally treats variables as strings of text, so unless you tell it otherwise with declare, your variables are just a bunch of letters to bash. However, when you start trying to do arithmetic with them, bash converts them to integers if it can. This makes it possible to do some fairly complex arithmetic in bash.

Integer arithmetic can be performed using the built-in letcommand or through the external expror bccommands. After setting the variable BIGNUMvalue to 1024, the three commands that follow would all store the value 64in the RESULTvariable. The bccommand is a calculator application that is available in most Linux distributions. The last command gets a random number between 0 and 10 and echoes the results back to you.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Linux Bible»

Представляем Вашему вниманию похожие книги на «Linux Bible» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Linux Bible»

Обсуждение, отзывы о книге «Linux Bible» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x