Sunteți pe pagina 1din 31

The Linux Shells Basic Commands

Operating Systems Laboratory Amir Saman Memaripour

The if Command
The built-in if command runs a command and checks the results. If the command was successful, it executes another set of commands. The only command normally used with the if command is test. There are also other uses of if command. The syntax for the basic if command is as follows: if test arguments ; then statements to run fi

The if Command
The keyword then is treated as a separate command, requiring a semicolon to separate it from the if command. The keyword fi appears after the final command to be executed inside the if. For example, the test -f command checks for the existence of a file: if test -f ./report.out ; then printf The report file ./report.out exists!\n fi

File Expressions
The built-in test command contains a wide variety of tests for files. It can test the type of file, the accessibility of the file, compare the ages of files or other file attributes. The following is a complete list of Bash file tests. File testing is commonly used in the sanity checks at the beginning of a script. They can be used to check that all files are present and readable (and writable, if necessary). All commands must be executable.

File Expressions
Option -b file -c file -d file -e file -f file -g file -h file or -L file -k file -p file -r file -s file Performed Action True if the file is a block device file True if the file is a character device file True if the file is a directory True if the file exists True if the file exists and is a regular file True if the file has the set-group-id permission set True if the file is a symbolic link True if the file has the sticky permission bit set True if the file is a pipe True if the file is readable (by your script) True if the file exists and is not empty

File Expressions
Option -S file -t fd -u file -w file -x file -O file -G file -N file f1 -nt f2 f1 -ot f2 f1 -ef f2 Performed Action True if the file is a socket True if the file descriptor is opened on a terminal True if the file has the set-user-id permission set True if the file is writable (by your script) True if the file is executable (by your script) True if the file is (effectively) owned by you True if the file is (effectively) owned by your group True if the file has new content (since the last time it was read) (newer than) True if file f1 is newer than f2 (older than) True if file f1 is older than f2 (equivalent file) True if file f1 is a hard link to f2

File Expressions
if test ! -x $who ; then printf $SCRIPT:$LINENO: the command $who is not available aborting >&2 exit 192 fi This script fragment ensures that the who command is executable!

Multiple Tests
Single tests can be combined together with -a (and) and -o (or) switches.
if test -f $TMP -a ! -w $TMP ; then printf $SCRIPT:$LINENO: the temp file $TMP exists and cannot be overwritten aborting >&2 fi

This is not exactly the same as


if test -f $TMP && test ! -w $TMP ; then printf $SCRIPT:$LINENO: the temp file $TMP exists and cannot be overwritten aborting >&2 fi

Multiple Tests
One situation that tends to confuse shell programmers is when mixing the not operator with -a or -o switch. In most computer languages, not takes precedence as a unary operator and executes first. In Bash, -a and -o take precedence over the not operator, causing the following test to always be false: if test ! -f $TMP -o -f $TMP ; then Bash interprets this command as if the file neither exists nor exists. This odd behavior is in accordance with the POSIX standard. To get the expected result, you must use parentheses. if test \( ! -f $TMP \) -o -f $TMP ; then

Square Brackets
Square brackets are an alternative form of the test command. Using square brackets makes your if commands easier to read. if [ -f $TMP -a ! -w $TMP ] ; then printf $SCRIPT:$LINENO: the temp file $TMP exists and cannot\ be overwritten aborting >&2 exit 192 fi

10

String Expressions
The test command can compare a pair of strings.
Option -z s -n s (or just s) s1 = s2 s1 != s2 s1 < s2 s1 > s2 Performed Action (zero length) True if the string is empty (not null) True if the string is not empty True if string s1 is equal to s2 True if string s1 is not equal to s2 True if string s1 is less than s2 True if string s1 is greater than s2

11

String Expressions
DAY=`date +%a` if [ $DAY = Mon ] ; then printf The weekend is over...get to work!\n fi

The -z (zero length) and -n (not zero length) switches are short forms of = and != , respectively. Notice that there are no greater than or equal to, or less than or equal to, operators. You can simulate these operators by combining the two tests with the a switch.

12

Arithmetic Expressions
The built-in let command performs math calculations. let expects a string containing a variable, an equals sign, and an expression to calculate. The result is assigned to the variable. $ let SUM=5+5 $ printf %d $SUM 10

13

Arithmetic Expressions
You dont need to use $ to expand a variable name in the string. let understands that any variable appearing on the right side of the equals sign needs to have its value substituted into the expression.
$ let SUM=SUM+5 $ printf %d $SUM 15 $ let SUM=$SUM+5 $ printf %d $SUM 20

14

Arithmetic Expressions
The optional dollar sign is a special feature of the let command and does not apply to other commands. If a variable is declared as an integer with the -i switch, the let command is optional.
$ SUM=SUM+5 $ printf %d\n $SUM 25

15

Arithmetic Expressions
The let command provides the four basic math operators, plus a remainder operator. Only integer expressions are allowed (no decimal points).
$ let RESULT=5 + 2 $ let RESULT=5 - 2 $ let RESULT=5 * 2 $ let RESULT=5 / 2 $ let RESULT=5 % 2

16

Logical Expressions
In let, true is represented by the value of 1, and false by 0. Any value other than 1 or 0 is treated as true, but the logical operators themselves only return 1 or 0. Remember that logical truth (a value greater than zero) is not the same as the success of a command (a status code of zero). In this respect, test and let are opposites of each other. To use logical negation at the shell prompt, you must disable the shell history option or Bash will interpret the ! as a history look-up request. $ let RESULT=!0 $ let RESULT=!1 $ let RESULT=1 && 0 $ let RESULT=1 || 0

17

Relational Operations
Unlike string comparisons, let provides a full complement of numeric comparisons. These are of limited value because most of comparisons are tested with the test command in the if command, resulting in two sets of tests. In logical expressions, 0 is a failure.
$ let RESULT=1 > 0 $ printf 1 greater than 0 is %d\n $RESULT 1 greater than 0 is 1 $ let RESULT=1 >= 0 $ printf 1 greater than or equal to 0 is %d\n $RESULT 1 greater than or equal to 0 is 1

18

Bitwise Operations
There is also a set of bitwise operators, as follows.
$ let RESULT=~5 $ printf bitwise negation of 5 is %d\n $RESULT bitwise negation of 5 is -6 $ let RESULT=5 >> 2 $ printf 5 left-shifted by 2 is %d\n $RESULT 5 left-shifted by 2 is 1

19

Self-Referential Operations
Self-referential operators are shorthand notations that combine assignment with one of the other basic operations. The operation is carried out using the assignment variable, and then the result is assigned to the assignment variable. For example, RESULT+=5 is a short form of RESULT=RESULT+5.
$ let RESULT=5 $ let RESULT+=5 $ printf The result is %d $RESULT The result is 10

20

Other let Features


Parentheses are allowed in the expressions.
$ let RESULT=(5+3)*2 $ printf The expression is %d $RESULT The expression is 16

Assignment in the let command is an operator that returns the value being assigned. As a result, multiple variables can be assigned at once.
$ let TEST=TEST2=5 $ printf The results are %d and %d\n $TEST $TEST2 The results are 5 and 5

21

Other let Features


let can evaluate more than one expression at a time. Several, small assignments can be combined on one line.
$ let SUM=5+5 SUM2=10+5

Excessive numbers of assignments in a single let command will lead to readability problems in a script. When each let is on a single line, its easier to look through the script for a specific assignment. The conditional expression operator (?) is shorthand for an if statement when one of two different expression are evaluated based on the left condition. Because this is a feature of the let command, it works only with numeric expressions, not strings. The following example constrains a truth value to a 1 or a 0.
$ let RESULT=VALUE > 1 ? 1 : 0

22

Other let Features


Double parentheses are an alias for let. They are used to embed let expressions as parameters in another command. The shell replaces the double parentheses with the value of the expression.
declare -i X=5; while (( X-- > 0 )) ; do printf %d\n $X Done

This script fragment prints a list of numbers from four to zero. The embedded let reduces X by one each time through the loop and checks to see when the value of X reaches zero.

23

Arithmetic Tests
The test command can compare numeric values, but it uses different operators than the ones used to compare string values. Because all shell variables are stored as strings, variables can either be compared as numbers or strings depending on the choice of operator. Perl programmers will find this similar to Perl. Bash will not report an error if string operators are used with integer variables.
$ RESULT=`ls -1 | wc -l` $ printf %d $RESULT 22

24

Arithmetic Tests
Option n1 -eq n2 n1 -ne n2 n1 -lt n2 n1 -le n2 n1 -gt n2 n1 -ge n2 Performed Action (equal) True if n1 is equal to n2 (not equal) True if n1 is not equal to n2 (less than) True if n1 is less than n2 (less than or equal) True if n1 is less than or equal to n2 (greater than) True if n1 is greater than n2 (greater than or equal) True if n1 is greater than or equal to n2

25

Pattern Recognition
Bash pattern recognition is called globbing. Globbing is used to match filenames given to a command, and it is also used by the Korn shell test command to match strings. $ ls *.txt notes.txt project_notes.txt The pattern-recognition feature works by supplying wildcard symbols that Bash will attempt to match to a string or a filename. The asterisk (*) character represents zero or more characters. The Korn shell test can be used to match the value of a variable to a string with an asterisk.

26

Pattern Recognition
COMPANY=Athabasca if [[ $COMPANY = A* ]] ; then printf The company name begins with a letter a A\n fi if [[ $COMPANY = Z* ]] ; then printf The company name begins with a letter a Z\n fi

This behavior doesnt work when quotation marks are used. Quotation marks tell the Korn shell test command not to interpret special characters. A test for A* would indicate a file named A*.

27

Pattern Recognition
The question mark (?) character is a wildcard representing any single character.
COMPANY=AIC if [[ $COMPANY = A?? ]] ; then printf The company name is 3 characters beginning with A\n fi

You can specify a set of characters using square brackets. You can list individual characters or ranges.
if [[ $COMPANY = [ABC]* ]] ; then printf The company name begins with a A, B or C\n fi

28

Pattern Recognition
You can separate lists of patterns by using vertical bar characters (|).
COMPANY=Champion Ltd if [[ $COMPANY = Champion*@(Ltd|Corp|Inc) ]] ; then

Syntax ?(pattern-list) *(pattern-list) +(pattern-list) @(pattern-list) !(pattern-list)

Performed Action Matches zero or one occurrence of the given patterns Matches zero or more occurrences of the given patterns Matches one or more occurrences of the given patterns Matches exactly one of the given patterns Matches anything except one of the given patterns

29

Pattern Recognition
Syntax [:alnum:] [:alpha:] [:ascii:] [:blank:] [:cntrl:] [:digit:] [:graph:] [:lower:] [:space:] [:upper:] [:xdigit:] Alphanumeric Alphabetic ASCII characters Space or tab Control characters Decimal digits Non-blank characters Lowercase characters Whitespace Uppercase characters Hexadecimal digits Performed Action

30

Assignment (5 points)
Write a shell script in order to convert Fahrenheit to Celsius.
TempCelsius = 5 * (TempFahrenheit 32) / 9

Deadline: December 11th, 10:00 AM How to deliver?! Via email to memarypour@gmail.com This assignment is mandatory!

31

S-ar putea să vă placă și