Linux Shell (5)

Embed Size (px)

Citation preview

  • 7/31/2019 Linux Shell (5)

    1/31

    The Linux ShellsBasic Commands

    Operating Systems Laboratory

    Amir Saman Memaripour

  • 7/31/2019 Linux Shell (5)

    2/31

    The if CommandThe built-in ifcommand runs a command and checks the

    results. If the command was successful, it executesanother set of commands. The only commandnormally used with the ifcommand is test. There are

    also other uses of ifcommand.

    The syntax for the basic ifcommand is as follows:

    if test arguments ; then

    statements to run

    fi

    2

  • 7/31/2019 Linux Shell (5)

    3/31

    The if CommandThe keyword then is treated as a separate command,

    requiring a semicolon to separate it from the ifcommand. The keyword fi appears after the finalcommand to be executed inside the if.

    For example, the test -f command checks for theexistence of a file:

    if test -f ./report.out ; then

    printf The report file ./report.out exists!\n

    fi

    3

  • 7/31/2019 Linux Shell (5)

    4/31

    File ExpressionsThe built-in test command contains a wide variety of

    tests for files. It can test the type of file, theaccessibility of the file, compare the ages of files orother file attributes. The following is a complete list of

    Bash file tests.

    File testing is commonly used in the sanity checks at thebeginning of a script. They can be used to check that

    all files are present and readable (and writable, ifnecessary). All commands must be executable.

    4

  • 7/31/2019 Linux Shell (5)

    5/31

    File ExpressionsOption Performed Action

    -b file True if the file is a block device file

    -c file True if the file is a character device file

    -d file True if the file is a directory

    -e file True if the file exists

    -f file True if the file exists and is a regular file

    -g file True if the file has the set-group-idpermission set

    -h fileor -L file True if the file is a symbolic link

    -k file True if the file has the sticky permission bit set-p file True if the file is a pipe

    -r file True if the file is readable (by your script)

    -s file True if the file exists and is not empty

    5

  • 7/31/2019 Linux Shell (5)

    6/31

    File ExpressionsOption Performed Action

    -S file True if the file is a socket

    -t fd True if the file descriptor is opened on a terminal

    -u file True if the file has the set-user-idpermission set

    -w file True if the file is writable (by your script)-x file True if the file is executable (by your script)

    -O file True if the file is (effectively) owned by you

    -G file True if the file is (effectively) owned by your group

    -N file True if the file has new content (since the last time it was

    read)f1 -nt f2 (newer than) True if file f1 is newer than f2

    f1 -ot f2 (older than) True if file f1 is older than f2

    f1 -ef f2 (equivalent file) True if file f1 is a hard link to f2

    6

  • 7/31/2019 Linux Shell (5)

    7/31

    File Expressionsif test ! -x $who ; then

    printf $SCRIPT:$LINENO: the command $who is notavailable aborting >&2

    exit 192

    fi

    This script fragment ensures that the who command isexecutable!

    7

  • 7/31/2019 Linux Shell (5)

    8/31

    Multiple TestsSingle 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 beoverwritten aborting >&2

    fi

    8

  • 7/31/2019 Linux Shell (5)

    9/31

    Multiple TestsOne situation that tends to confuse shell programmers is

    when mixing the not operator with -a or -o switch. In mostcomputer languages, not takes precedence as a unaryoperator and executes first. In Bash, -a and -o take

    precedence over the not operator, causing the followingtest to always be false:

    if test ! -f $TMP -o -f $TMP ; then

    Bash interprets this command as if the file neither exists norexists. This odd behavior is in accordance with the POSIXstandard. To get the expected result, you must useparentheses.

    if test \( ! -f $TMP \) -o -f $TMP ; then

    9

  • 7/31/2019 Linux Shell (5)

    10/31

    Square BracketsSquare brackets are an alternative form of the test command.

    Using square brackets makes your if commands easier toread.

    if [ -f $TMP -a ! -w $TMP ] ; thenprintf $SCRIPT:$LINENO: the temp file $TMP exists andcannot\

    be overwritten aborting >&2

    exit 192

    fi

    10

  • 7/31/2019 Linux Shell (5)

    11/31

    String ExpressionsThe testcommand can compare a pair of strings.

    11

    Option Performed Action

    -z s (zero length) True if the string is empty

    -n s(or just s) (not null) True if the string is not empty

    s1 = s2 True if string s1 is equal to s2

    s1 != s2 True if string s1 is not equal to s2

    s1 < s2 True if string s1 is less than s2

    s1 > s2 True if string s1 is greater than s2

  • 7/31/2019 Linux Shell (5)

    12/31

    String ExpressionsDAY=`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 areshort forms of = and != , respectively. Notice that

    there are no greater than or equal to, or less than orequal to, operators. You can simulate theseoperators by combining the two tests with the aswitch.

    12

  • 7/31/2019 Linux Shell (5)

    13/31

    Arithmetic ExpressionsThe built-in let command performs math calculations.

    let expects a string containing a variable, an equalssign, and an expression to calculate. The result isassigned to the variable.

    $ let SUM=5+5

    $ printf %d $SUM

    10

    13

  • 7/31/2019 Linux Shell (5)

    14/31

    Arithmetic ExpressionsYou dont need to use $ to expand a variable name in the

    string. let understands that any variable appearing on theright side of the equals sign needs to have its valuesubstituted into the expression.

    $ let SUM=SUM+5

    $ printf %d $SUM

    15

    $ let SUM=$SUM+5

    $ printf %d $SUM

    20

    14

  • 7/31/2019 Linux Shell (5)

    15/31

    Arithmetic ExpressionsThe 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 -iswitch,

    the letcommand is optional.

    $ SUM=SUM+5

    $ printf %d\n $SUM

    25

    15

  • 7/31/2019 Linux Shell (5)

    16/31

    Arithmetic ExpressionsThe let command provides the four basic math

    operators, plus a remainder operator. Only integerexpressions 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

  • 7/31/2019 Linux Shell (5)

    17/31

    Logical ExpressionsIn let, trueis represented by the value of 1, and falseby 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 thesuccess of a command (a status code of zero). In this respect, testand letareopposites of each other.

    To use logical negation at the shell prompt, you must disable the shell historyoption 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

  • 7/31/2019 Linux Shell (5)

    18/31

    Relational OperationsUnlike string comparisons, let provides a full complement of

    numeric comparisons. These are of limited value becausemost of comparisons are tested with the test command inthe if command, resulting in two sets of tests. In logicalexpressions, 0 is a failure.

    $ let RESULT=1 > 0

    $ printf 1 greater than 0 is %d\n $RESULT1 greater than 0 is 1

    $ let RESULT=1 >= 0

    $ printf 1 greater than or equal to 0 is %d\n $RESULT1 greater than or equal to 0 is 1

    18

  • 7/31/2019 Linux Shell (5)

    19/31

    Bitwise OperationsThere 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

  • 7/31/2019 Linux Shell (5)

    20/31

    Self-Referential OperationsSelf-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 ofRESULT=RESULT+5.

    $ let RESULT=5

    $ let RESULT+=5

    $ printf The result is %d $RESULT

    The result is 10

    20

  • 7/31/2019 Linux Shell (5)

    21/31

    Other letFeaturesParentheses are allowed in the expressions.

    $ let RESULT=(5+3)*2

    $ printf The expression is %d $RESULT

    The expression is 16

    Assignment in the letcommand is an operator that returns the value beingassigned.

    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

  • 7/31/2019 Linux Shell (5)

    22/31

    Other letFeatureslet 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 toreadability problems in a script. When each let is on a single line, itseasier to look through the script for a specific assignment.

    The conditional expression operator (?) is shorthand for an if statementwhen one of two different expression are evaluated based on the leftcondition. Because this is a feature of the letcommand, it works only withnumeric expressions, not strings. The following example constrains atruth value to a 1 or a 0.

    $ let RESULT=VALUE > 1 ? 1 : 0

    22

  • 7/31/2019 Linux Shell (5)

    23/31

    Other letFeaturesDouble parentheses are an alias for let. They are used to embed let

    expressions as parameters in another command. The shellreplaces 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. Theembedded let reduces X by one each time through the loop andchecks to see when the value of X reaches zero.

    23

  • 7/31/2019 Linux Shell (5)

    24/31

    Arithmetic TestsThe testcommand can compare numeric values, but it

    uses different operators than the ones used to comparestring values. Because all shell variables are storedas strings, variables can either be compared as

    numbers or strings depending on the choice ofoperator. Perlprogrammers will find this similar to Perl.Bash will not report an error if string operators areused with integer variables.

    $ RESULT=`ls -1 | wc -l`

    $ printf %d $RESULT

    22

    24

  • 7/31/2019 Linux Shell (5)

    25/31

    Arithmetic Tests

    25

    Option Performed Action

    n1 -eq n2 (equal) True if n1 is equal to n2

    n1 -ne n2 (not equal) True if n1 is not equal to n2

    n1 -lt n2 (less than) True if n1 is less than n2

    n1 -le n2 (less than or equal) True if n1 is less than or equal to n2

    n1 -gt n2 (greater than) True if n1 is greater than n2

    n1 -ge n2 (greater than or equal) True if n1 is greater than or equal to n2

  • 7/31/2019 Linux Shell (5)

    26/31

    Pattern RecognitionBash pattern recognition is called globbing. Globbing is

    used to match filenames given to a command, and itis also used by the Korn shell test command to matchstrings.

    $ ls *.txt

    notes.txt project_notes.txt

    The pattern-recognition feature works by supplying

    wildcard symbols that Bash will attempt to match to astring or a filename. The asterisk (*) characterrepresents zero or more characters. The Korn shell testcan be used to match the value of a variable to a stringwith an asterisk.

    26

  • 7/31/2019 Linux Shell (5)

    27/31

    Pattern RecognitionCOMPANY=Athabasca

    if [[ $COMPANY = A* ]] ; then

    printf The company name begins with a letter a A\n

    fiif [[ $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 testcommand not to interpretspecial characters. A testfor A* would indicate a file named A*.

    27

  • 7/31/2019 Linux Shell (5)

    28/31

    Pattern RecognitionThe 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 individualcharacters or ranges.

    if [[ $COMPANY = [ABC]* ]] ; then

    printf The company name begins with a A, B or C\n

    fi

    28

  • 7/31/2019 Linux Shell (5)

    29/31

    Pattern RecognitionYou can separate lists of patterns by using vertical bar characters

    (|).

    COMPANY=Champion Ltd

    if [[ $COMPANY = Champion*@(Ltd|Corp|Inc) ]] ; then

    29

    Syntax Performed Action

    ?(pattern-list) Matches zero or one occurrence of the given patterns

    *(pattern-list) Matches zero or more occurrences of the given patterns

    +(pattern-list) Matches one or more occurrences of the given patterns

    @(pattern-list) Matches exactly one of the given patterns

    !(pattern-list) Matches anything except one of the given patterns

  • 7/31/2019 Linux Shell (5)

    30/31

    Pattern Recognition

    30

    Syntax Performed Action

    [:alnum:] Alphanumeric

    [:alpha:] Alphabetic

    [:ascii:] ASCII characters

    [:blank:] Space or tab[:cntrl:] Control characters

    [:digit:] Decimal digits

    [:graph:] Non-blank characters

    [:lower:] Lowercase characters[:space:] Whitespace

    [:upper:] Uppercase characters

    [:xdigit:] Hexadecimal digits

  • 7/31/2019 Linux Shell (5)

    31/31

    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 [email protected]

    This assignment is mandatory!

    31

    mailto:[email protected]:[email protected]