CS203 Lab 1 -- Introduction to the Command-Line Interface (CLI)


Lab Goal:

  • Learn what the Command-Line Interface (CLI) is and why it is important;
  • Gain experience using the CLI to control your account;
  • Learn how to write shell scripts to automate common tasks;

While you walk through this lab, you should be trying out the examples in a shell terminal. Once you login to linux you can start a terminal by:
  • clicking the framed black box at the bottom of the screen,
  • right-click then picking terminal,
  • or go to the applications menu then pick terminal.


Introductory Material for the Command-Line Interface (CLI)

This section, which is prior to the actual assignments, will give you the foundational information needed to perform many of the functions available in the CLI. Read it carefully, try the examples, and refer to it when you execute the Lab tasks.

  • Be careful with capitalization - file names and commands are case sensitive.
  • Spaces in the command-line are treated as separators. To force the command line to ignore that, for example if a file name has a space in it, use quotation marks or a backslash for each space. Better yet, do not use spaces in filenames!!!
      $ more "example with spaces.txt"       # File name with spaces and quotes.
      This file contains gibberish.
    
      $ more example with spaces.txt         # File name with spaces and no quotes.
      example: No such file or directory
      with: No such file or directory
      spaces.txt: No such file or directory
    
      $ more example\ with\ spaces.txt       # File name with spaces using a back slash.
      This file contains gibberish.
    
  • echo is a command that you will use frequently. It outputs to the command line the argument
  • $ echo "Hello there"
    Hello there
    $
    
  • A few handy shortcuts using control characters:

    The keyboard contains keys called modifier keys and these are labeled things like ctrl (or control) and alt (for alternate). These are type in combination with other keys to "modify" the meaning of that key. These combinations produce control characters that are special keyboard commands for controlling the computer.

    • ctrl-c - aborts an application (almost) instantaneously. Note that - ctrl-c is your friend if your software is caught in an infinite loop, because it will halt something that might be blocking your ability to do something.
    •  
    • ctrl-d - sends and end of file (EOF) marker.
      • If typed in the shell, it will exit the shell as if the exit command was typed. One way for you to think about this, typing ctrl-d indicates to the shell that you are using that the current file is as the end.
      • Another use is with the cat program, that is short for concatenation and allows you to concatenate files together. This includes taking a number of lines from the command-line and concatenating and adding them to an empty file created by the cat command. (illustrated below)
        $ cat > some_file.txt
        I am adding one line,
        a second line and
        a third line.       # type ctrl-d
        $
        
        The ctrl-d is pressed at the end to exit out of the program, writing those lines to the file some_file.txt
    •  
    • ctrl-p - Display the previous command, using this key combination previous commands will be displayed in order from the command-line history.
      • Using this command you can "march" back in history through the previous commands by using ctrl-p repeatedly.
    •  
    • ctrl-s - Go back to the next most recent command.
    •  
    • ctrl-n - Next command in history.
      • Use this if you have marched back in history and wish to come forward again.

Variables

The environment variables are system variables that influence how the software works in the shell.

  • Environment variables can be used for the shell current session only or set be for all sessions.
  • Use the command env to see the environment variables and settings for your current session. Below is an example run of this command and the following environment variables displayed. Note - this is a reduced list from what was actually displayed.
      $ env
      USER=bob
      PWD=/home/bob
      HOME=/home/bob
      SSH_CLIENT=64.121.201.190 65027 22
      SSH_TTY=/dev/pts/0
      MAIL=/var/spool/mail/bob
      TERM=xterm-256color
      SHELL=/bin/bash
      SHLVL=1
      LOGNAME=bob
      PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/bob/.local/bin:/home/bob/bin
      
      $
    
  • To echo a variable, precede the name with a $ character.
      $ echo $HOME
      /home/bob
    
  • You can assign values or otherwise alter variables so that the new information is used throughout the session.
      $ TEST_VARIABLE=hi
      $ echo $TEST_VARIABLE
      hi
    
  • You can make these variable assignments permanent by placing them in your specific user environment files, called: .bashrc and .bashrc_profile. Note - these files are hidden in the file system, which is specified by a dot at the front of the file name. These are actually script files that are run for configuring your shell by the system during the following cases.
    • .bashrc_profile - is run by the system when you first login.
    • .bashrc - is run every time a new shell is created.
Some additional examples:
  • MY_PROJECT=/home/bob/my_project - Defines the variable "MY_PROJECT" with a particular directory location "/home/bob/my_project"
  •  
  • MY_CLASSES=$MY_PROJECT/bin - Defines the variable MY_CLASSES with the value of MY_PROJECT with /bin appended to the end (this will be /home/bob/my_project/bin if MY_PROJECT is defined as above)
  •  
  • The value of MY_CLASSES can be used by commands by prefixing a dollar sign, "$", to the variable name, as in the following examples:
    • cd $MY_PROJECT - Changes your current working directory, or the location of the directory structure you are in, to the value of the MY_PROJECT variable.
    • echo $MY_PROJECT - Prints out the value of MY_PROJECT (this will be /home/bob/my_project if MY_PROJECT is defined as above.)
    These commands are illustrated in the following, using the pwd command to identify where you are in the directory structure.
      $ pwd
      /home/bob
    
      $ MY_PROJECT="/home/bob/example"
    
      $ echo $MY_PROJECT
      /home/bob/example
    
      $ cd $MY_PROJECT
    
      $ pwd
      /home/bob/example
    
Common environment variables:
  • LOGNAME - the variable with the session user's login name
  •  
  • LANG - the language to use (e.g. en_US.UTF-8 would be the value of the LANG variable for English and UTF-8 character encoding)
  •  
  • PATH - this is one of the most important environment variables.
    • The contents of the PATH variable specify a set of directories in which executable programs are located.
    • The Bash shell uses this variable to determine which directories to search when executable files need to be accessed/run.
  •  
  • PWD - present working directory
  •  
  • BASH - the full pathname used for this instance of Bash
  •  
  • BASH_VERSION - the version of this instance of Bash
  •  
  • HOME - the home directory of the user
  •  
  • RANDOM - a random integer between 0 and 32767. A value assigned to it will seed the random number generator
All these environment variables can all be accessed in the ways you have seen above.
  $ echo $LOGNAME
  bob
  $ echo $PATH
  /usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
  $ echo $LANG
  en_US.UTF-8

But it is important to remember it is the convention to use all caps when creating a variable. Also, you can define variables as you have done in Java, but you MUST access it with a prepended $ character.

There are many predefined system variables and you can see more at internal variables.

Single vs. Double quoted strings:

A very neat trick that many scripting languages have inherited from shell scripts is the single- and double-quoted operations.

  • Double quote will "interpret" the string as if it were a line of code, resolving things like variables.
  • Single quotation marks indicate that there should be no interpretation of any text in the quotes. What you see is what you get.
For example:
 
  $ NAME="Linda"
  $ echo "my name is $NAME"
  my name is Linda
  $ echo 'my name is $NAME'
  my name is $NAME

Working with the directory structure

Use the ls command to "list" the contents of a directory. This command comes in three flavors using switches to toggle different behaviors:

  • "ls" is just the vanilla version, displaying just file names.
  • "ls -l" is a long listing will provide detailed information about each listed item (file, directory, etc.).
  • "ls -la" is also a long listing but will also print hidden files starting with a dot.

$ ls -la
total 180
  drwx------.   13    bob   user     4096   Aug 26 10:50    .
  drwxr-xr-x.    3    bob   user       19   Feb 10  2017    ..
  -rw-r--r--.    1    bob   user    81529   Sep 10  2016    20160910.tgz
  -rw-------.    1    bob   user     9938   Aug 23 10:35    .bash_history
  -rw-r--r--.    1    bob   user      193   May 17  2016    .bash_profile
  -rw-r--r--.    1    bob   user      231   May 17  2016    .bashrc
  -rwxrwxrwx     1    bob   user       28   Aug 23 08:28    testitem.txt
# ||-||-||-|     ^     ^     ^         ^     ^                ^
# | |  |  |      |     |     |         |     |                |
# | |  |  |      |     |     |         |     |                file name, note the dots
# | |  |  |      |     |     |         |     date that the file was modified
# | |  |  |      |     |     |         file size in bytes
# | |  |  |      |     |     group that the user belongs to
# | |  |  |      |     owner of the files (typically you)
# | |  |  |      number of links to the file (something that will be talked about later)
# | |  |  permissions for the world
# | |  permissions for the member of the group (specified above)
# | permissions for file owner: r = read, w = write, x = execute, - = no permission
# type of file: - = normal file, d = directory, l = symbolic link, and others...

The file system is hierarchically organized as a tree structure. Below is an example of a one user's file system using the command tree

  home
  \-- bob
      |-- 20160910.zip
      |-- bin
      |   |-- mount_bunter.sh
      |   \-- unmount_bunter.sh
      |-- bin.tar
      |-- catch_rsync.txt
      |-- class_lists.tar
      |-- fancy_reports_20160910
      |   |-- Data_Current.csv
      |   |-- Data_History.csv
      |   \-- Current_Family_Members.csv
      |-- example
      |-- gluster_fstability
      |-- ldapConf
      |   |-- basedomain.ldif
      |   |-- domain.ldif
      |   |-- rootpw.ldif
      |   \-- ids_non_family.ldif
      |-- mount_bunter.sh
      \-- testitem.txt
  • navigating between directories is navigation up and down the tree.
  • The current working directory is the directory associated with the processes being worked upon (in which the user is working).
  • The command pwd will output the path for the current working directory, illustrated in the variable section.
  • To identify where in the tree the file or directory is located, a path is given.
    • This path can be absolute or relative.
    • An absolute path shows the location of a file or directory relative to the root directory. It is not dependent upon the current working directory.
    • A relative path provides the location relative to the current working directory.
  • Example of an absolute path:
      $ pwd
      /usr2/plotnickl
    
  • Example of using a relative path:
    $ ls
    afile.txt                    bfile.txt       DoubleLLV2.c  Lab3              segmentationError
    a.out                        checkingArgs    factorial     myfile.txt        segmentationError.c
    ArchiveMisc                  checkingArgs.c  factorial.c   Myfirstscript.sh  SingleLLV2
    ArchiveSingleLLstructNode    Compile.sh      Lab1          regex2.sh         SingleLLV2.c
    ArchiveSingleLLstructNode.c  DoubleLLV2      Lab2          regex.sh
    
    $ cd Lab3
    
    $ pwd
    /usr2/plotnickl/Lab3
    
    
    Process shown:
    1. ls command determine the files and subdirectories in the current working directory.
    2. cd command is given with the name of one of the subdirectories changing the current working directory to the subdirectory (which in the cd command was given as a relative path - i.e. not the path from the root).
    3. pwd command shows the current working directory which is Lab3 and the path to it from the root (i.e. the absolute path)
  • There are a variety of symbols that can be used in navigating through the file system:

    • ./ - shortcut for the current path
    • ~ (tilde) - shortcut to refer to your home directory
    • . (dot or period) - reference to the current directory.
    • .. (two dots/two periods) reference to the parent directory of the current directory.

    These commands can be mixed and matched to move around or for identifying files, so using the change directory command (cd), you can do the following. Note - This example uses the above example directory tree.

      $ ls                         # this lists my home directory
       20160910.tgz         bin.tar          fancy_reports_20160910   
       gluster_fstability   testitem.txt     mount_bunter.sh
       bin                  catch_rsync.txt  class_lists.tar
       example              ldapConf
    
      $ pwd                         # this is giving me my working directory
      /home/bob
    
      $ cd fancy_reports_20160910/  # this will change the current directory to the named directory
      $ ls
      Data_Current.csv  Data_History.csv  Current_Family_Members.csv
    
      $ pwd
      /home/bob/fancy_reports_20160910
      
      $ cd ../ldapConf/             # this will change the directory to one up in 
                                    # the tree and back down into a different location
      
      $ ls
      basedomain.ldif   domain.ldif  rootpw.ldif  ids_non_family.ldif
      
      $ pwd
      /home/bob/ldapConf
      
      $ cd ~                        # this returns home
      
      $ pwd
      /home/bob
      
      $ cd ..                       # this goes one up in the directory
      
      $ pwd
      /home
      
      $ cd                          # this will also take you home
      $ pwd
      /home/bob
      
    

    super hint:

    as you start typing a path in Bash, if you depress the tab key auto complete will complete the path. If it doesn't, it means there is more than one possible path. If you depress the tab key again, those possibilities will be displayed. Continue typing until the one you want is unique and then try to invoke auto complete again.

    Commands that affect permissions:

    • chmod 755 some_file - Changes the permissions of "some_file" to be read/write/execute (rwx) for the owner, and read/execute (rx) for the group and the world. The specified numbers break down as follows:
      • each number maps as a binary representation of the permission set for the owner, group, and everyone respectively;
      • 755maps to:
        • 7 => 111 (binary) => rwx => read/write/execute permissions for the owner,
        • 5 => 101 (binary) => r-x => read/execute permissions for both the group and everyone else
    • chgrp admins some_file - Makes "some_file" belong to the group "admins"
    • chown cliff some_file - Makes "cliff" the owner of "some_file"
    • chown -R cliff some_dir - Makes "cliff" the owner of "some_dir" and everything in its directory tree (all the files and subdirectories recursively in "some_dir")

Getting help

There are a variety of mechanisms for help: man, info, apropos, whatis, whoami, and where.
  • apropos lists the topics in the standard built-in manual that are related to the subject of the keywords. The syntax is apropos keywords
  • whatis - similar to apropos but searches for whole words that match the keywords.
    • It is useful to obtain brief descriptions about commands for which you know the exact name.
  • man - the command to search and print results from the system manual.
    • syntax - man item
    • For more information, including the available options, issue the command man man
    • If you use the -k option (e.g. man ls -k) only the name, synopsis, and description will be printed.
  • example (not all output shown) of man ls
        LS(1)                                         User Commands                                        LS(1)
    
        NAME
               ls - list directory contents
    
        SYNOPSIS
               ls [OPTION]... [FILE]...
    
        DESCRIPTION
               List information about the FILEs (the current directory by default).  Sort entries alphabetically
               if none of -cftuvSUX nor --sort is specified.
    
               Mandatory arguments to long options are mandatory for short options too.
    
               -a, --allinfo
                      do not ignore entries starting with .
    
               -A, --almost-all
                      do not list implied . and ..
    
               --author
                      with -l, print the author of each file
    
               -b, --escape
                      print C-style escapes for nongraphic characters
    
               --block-size=SIZE
                      scale sizes by SIZE before printing them; e.g., '--block-size=M' prints sizes in units  of
                      1,048,576 bytes; see SIZE format below
    
               -B, --ignore-backups
                      do not list implied entries ending with ~
        
  • info - outputs the info page for a command or item.
    • Some items may not have man pages but might have an info page.
    • The syntax is as for man.
    • example of info ls:
          Next: dir invocation,  Up: Directory listing
      
          10.1 ls: List directory contents
          ==================================
      
          The "ls" program lists information about files (of any type, including
          directories).  Options and file arguments can be intermixed arbitrarily,
          as usual.
      
             For non-option command-line arguments that are directories, by
          default "ls" lists the contents of directories, not recursively, and
          omitting files with names beginning with ".".  For other non-option
          arguments, by default "ls" lists just the file name.  If no non-option
          argument is specified, "ls" operates on the current directory, acting as
          if it had been invoked with a single argument of ".".
      
             By default, the output is sorted alphabetically, according to the
          locale settings in effect.(1)  If standard output is a terminal, the
          output is in columns (sorted vertically) and control characters are
          output as question marks; otherwise, the output is listed one per line
          and control characters are output as-is.
      
             Because "ls" is such a fundamental program, it has accumulated many
          options over the years.  They are described in the subsections below;
          within each section, options are listed alphabetically (ignoring case).
          The division of options into the subsections is not absolute, since some
          options affect more than one aspect of the "ls" operation.
      
             Exit status:
      
               0 success
               1 minor problems  (e.g., failure to access a file or directory not
          -----Info: (coreutils)ls invocation, 57 lines --Top--------------------------------------------------------
          Welcome to Info version 6.3.  Type H for help, h for tutorial.
          
    • whoami - user name (login name) of the owner of the current session
      • example:
          $ whoami
          plotnickl
        

Manipulating Files

Use man command to obtain more information about the following example commands:

Command Syntax Function Notes
cp oldfile newfile copy oldfile to new file source and destination files in same directory
rm filename remove file(s) must have write permission for file and its folder
rm -r directoryname remove a directory(ies) and its files to suppress prompt for each file, use the option -rg
rmdir directoryname remove a directory or directories directory must be empty
mkdir directoryname create directory(ies) directory(ies) must not already exist
mv sourceFile destinationDirectory move file to directory paths required unless both are in the current directory

WARNING: there is no "undo". Be careful. Avoid removing using wildcard expressions (e.g. *.txt)

Viewing and editing files

Command Syntax Description
cat filename copy Print the contents of the specified file to the screen (one or more files can be specified and each will be printed to the screen - one concatenated with the other
more filename
  1. Print the contents of the specified file to the screen
  2. pause once the contents have filled the available screen real estate before printing more
  3. when paused:
    • ENTER = move one line down
    • SPACEBAR = page down
    • q = quit printing file(s)
less filename Like more, but you can move forwards and backwards throughout the file using the arrow, page-up, and page-down keys (this utility is not available on all systems)
nano filename edit a file using the nano editor. A description of use is further in the document
head filename Print the first few lines of a file
head -n filename Print the first n lines of a file
tail filename Print the last few lines of a file
tail -n filename Print the last n lines of a file

Basics of the nano editor

Opening nano

  • Syntax: nano filename.
  • if the file exists, nano opens with it in the editor
  • if the file does not exist, nano creates it
  $ nano HelloWorld.sh
  • short-cuts for commands at the bottom of the editing screen:
  •     GNU nano 2.8.4                File: HelloWorld.sh                           
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
                                       [ New File ]
      ^G Get Help    ^O Write Out   ^W Where Is    ^K Cut Text    ^J Justify
      ^X Exit        ^R Read File   ^\ Replace     ^U Uncut Text  ^T To Linter
    

    enter text

  • enter or edit file content
  • a "what you see is what you get" editor (wysiwyg):
  • what you type or paste goes directly into the text input unless you modify with a key shown at the bottom of the editing screen
  •   GNU nano 2.8.4                File: HelloWorld.sh                 Modified  
    
    #!/bin/bash
    echo "Hello
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    File Name to Write: HelloWorld.sh                                             
    ^G Get Help        M-D DOS Format     M-A Append         M-B Backup File
    ^C Cancel          M-M Mac Format     M-P Prepend        ^T To Files
    

    save file

  • Write Out (ctrl-o) to save file
    • editor responds by outputting "file to write:"
    •     GNU nano 2.8.4                File: HelloWorld.sh                           
      
        #!/bin/bash
        echo "Hello"
      
      
      
      
      
      
      
      
      
      
      
      
      
      
                                      [ Wrote 2 lines ]
        ^G Get Help    ^O Write Out   ^W Where Is    ^K Cut Text    ^J Justify
        ^X Exit        ^R Read File   ^\ Replace     ^U Uncut Text  ^T To Linter
      
    • press enter to save
    • editor responds with number of lines written

    Getting help with nano

  • while in the editor, ctrl-g brings up a help screen
  •                               Main nano help text                             
    
     The nano editor is designed to emulate the functionality and ease-of-use
     of the UW Pico text editor.  There are four main sections of the editor.
     The top line shows the program version, the current filename being
     edited, and whether or not the file has been modified.  Next is the main
     editor window showing the file being edited.  The status line is the
     third line from the bottom and shows important messages.  The bottom two
     lines show the most commonly used shortcuts in the editor.
    
     Shortcuts are written as follows: Control-key sequences are notated with
     a '^' and can be entered either by using the Ctrl key or pressing the Esc
     key twice.  Meta-key sequences are notated with 'M-' and can be entered
     using either the Alt, Cmd, or Esc key, depending on your keyboard setup.
     Also, pressing Esc twice and then typing a three-digit decimal number
     from 000 to 255 will enter the character with the corresponding value.
     The following keystrokes are available in the main editor window.
     Alternative keys are shown in parentheses:
    
    ^G    (F1)	Display this help text
    ^X    (F2)	Close the current file buffer / Exit from nano
    ^O    (F3)	Write the current file to disk
    ^R    (F5)	Insert another file into the current one
    
    
    ^X Close       ^W Where Is    ^P Prev Line   ^Y Prev Page   M-\ First Line
    ^L Refresh     M-W WhereIs Nex^N Next Line   ^V Next Page   M-/ Last Line
    

    Exit editor

    Type ctrl-x to exit the editor and return to the command line.

    Pipes

    The pipe symbol "|" (shift+backslash on most keyboards) is used to direct the output of one command to the input of another. Examples:

    • ls -l /etc | more
      • Takes the output of the long format directory list command ls -l /etc and pipes it through the "more" command.
      • In this case a very long list of files can be viewed a page at a time.
    • du /etc | sort -n | tail -n 5
      • uses some tools we haven't introduced, but shows an example of chaining together simple commands.
      • du /etc lists the sizes of all files and directories in the directory /etc.
      • The output from this command is then piped through sort -n, which orders the output from smallest to largest size.
      • that output is piped through tail -n 5, which displays only the last 5 lines of its input (which will be the 5 largest items in the /etc directory).

    Redirection

    The redirection directives, > and >> can be used on the output of most commands to direct their output to a file.
    Examples:

    • head -n 10 some_file > new_file - Redirects the output of the head command (detailed above) to a file "new_file"
    • head -n 10 some_file >> existing_file - Redirects the output of the head command to the end of "exist_file"

    ASSIGNMENTS

    General Instructions for Assignment Tasks:

    As you complete the subtasks below, copy/paste, either screenshots or the text in the CLI, into the report document the invocation and execution of the commands.

    • You will submit this document to Moodle as a pdf compressed in a tar file, which is described at the end of the lab.
    • Be certain to follow the submission instructions.

    TASK 1: using common commands in the Bash shell:

    The general form for a command expression in the command line is:

       cmd switch(es) argument(s)

    • Switches are modifiers that allow you to switch on different behavior and typically begin with at "-" (dash).
    • The available switches and number of arguments are specific to each command.
    • A switch is a minus sign followed by a single lower-case letter.

    Steps for Task 1

    1. Open a terminal, described at the top of this lab.
    2.  
    3. Directories exercise : Create a path specifier for a file named "my_file" in a directory named "my_dir" in a user's home directory. Do on paper - you will not have that directory. Submit in your pdf document.

      File and directory paths are specified using the forward slash "/" to separate directory and file names in the path.

          /               -- "root" directory
          /etc            -- directory "etc" (sub-directory of the root directory)
          /etc/default    -- a file or subdirectory named "default" in the "/etc" directory
          ~               -- shorthand for the current user's HOME directory (usually 
                             "/home/")
          ~/something     -- a file or directory named "something" located in the user's 
                             HOME directory
          .               -- A shortcut path specification which refers to the current 
                             working directory (see below)
          ..              -- A shortcut path specification which refers to the parent of the 
                             current working directory
      
    4. Determine the current shell by typing the command echo $SHELL
    5.  
    6. Determine the current working directory (pwd command)
    7.  
    8. Now issue the echo $Shell again without retyping it.
      1. The commands are stored so use the up and down arrows to access a previous (in this session) command.
      2. edit by using the right and left arrows.
    9.  
    10. Create and execute the commands necessary to perform the following actions:
      1. Set the variable "NAME" to your name
      2. Print a greeting to yourself using the echo command and the NAME variable
      3. Create a directory for storing files:
        1. Create a new subdirectory with mkdir Lab1files.
          1. demonstrate, by listing the current directory contents, it was done.
        2. Navigate between the starting directory and new directory as follows:
          1. cd Lab1files - navigate to the Lab1files directory
          2. cd .. - move up a level to the parent directory
          3. repeat the above 2 steps a few times. Stop with Lab1files as current directory
          4. Show the current directory.
        3. Create a simple text file in the new directory by one of the these methods:
        4. Use the cat command to create a new text file. Use man to review the help for cat
        5. Create a new text file by entering cat > myfile.txt in the command line. Note the following:
          1. you MUST have the .txt extension
          2. now be in a state to type content into the file
          3. The ">" symbol is a re-directive.
            • The single > redirects to a new file (creates the file) while >> redirects to the end of an existing file
    11.  
    12. Enter some content (the content is unimportant, but remember, I will see it in your screenshots/copy paste!!).
    13.  
    14. Type <ctrl>D to exit the file and return to the command line.
    15.  
    16. Type cat myfile.txt to display the file contents.
    17.  
    18. Edit myfile in the nano editor by typing nano myfile.txt
      1. Hints for using nano are above.
      2. if myfile.txt does not exist, it will be created.
    19.  
    20. Edit the file to add another line of text
    21.  
    22. save the file and exit:
      1. Save the file by using the command to "Write Out" as shown at the bottom of the nano editor.
    23.  
    24. Cat the file
    25.  
    26. Navigate to the home directory:

      use the ls command to display the contents of the home directory; use at least one switch (option)

      1. switch -a will show hidden files in the list displayed
      2. switch -l will show a more complete set of file information.
    27.  
    28. Create directory myNewDirectory as a subdirectory in the home directory
    29.  
    30. Create a simple text file textfile2.txt in the new directory.
      1. add content of a brief paragraph
    31.  
    32. Create a copy of the file in the same directory - cp textfile2.txt copytextfile2.txt while in myNewDirectory
    33.  
    34. Use ls and cat to verify the copy
    35.  
    36. Delete the Lab1files directory and its files.
      • refer to the Manipulating Files section above for hints
    37.  
    38. Verify that there is a subdirectory of the home directory named MyNewDirectory that has 2 text files in it.
    39.  
    40. Create the command necessary to change the permissions on the textfile2.txt file you created above so that
      • Its owner can read, write and execute it
      • its group can read and write it
      • everyone else can neither read, write, nor execute it
    41.  
    42. Searching for files: to find files within the filesystem use the "find" command.
      • This will search a given directory and its subdirectories for the arguments to the command.
      • find search_path -name some_name - This searches "search_path" for items named "some_name"
      • find . -name aaa.txt - Finds all the files named aaa.txt in the current directory or any subdirectory tree
      • find / -name vimrc - Find all the files name 'vimrc' anywhere on the system
      • find /usr/bin -name "*git*" - Find all files whose names contain the string "git" which exist within the "/usr/bin" directory tree.
        • the asterisks ('*') in a search string will be matched to any string, including the empty string - this allows for the search to locate items with "git" anywhere in the name
      • Exercise: search all the files in the home directory and report any filenames with the string "ll" in them.
    43.  
    44. Searching for strings in files by using the grep command
      • grep "find me" some_file - prints all the lines in "some_file" that contain the string "find me"
      • ls /etc | grep a - prints all the files or directories in the "/etc" directory that have the letter 'a' in their name
        • uses a pipe
      • Exercise: Create and execute a command that will look at all of the files in the home directory and print any file names that have the string "ell" in their names.

    Task 2: Writing and using Bash shell scripts

    Often, we perform the same tasks repeatedly. Rather than typing the commands in, one at a time, each time we wish to do this sequence of tasks, we can create what is called a script which is a file that has the commands in it. Then we need only execute the script (with a single command) to cause execution of the commands we want.

    Steps for task 2:

    1. Navigate to the home directory. Then using the nano editor, create a file with the content as shown below and save it as myfirstscript.sh
        #!/bin/bash
        #my first script
        echo "Welcome, $1, to my first script"
        echo "The current directory is "
        pwd
        echo "The contents of the directory are:"
        ls
        k=1
        while [ $k -le 4 ]
         do
            echo "we are counting $k"
            ((k++))
        done
        echo "$1,Thank you for using this script"
      
      Please note the following things:
      • $1 in the script is a variable representing the first argument of the script.
      • the ./ is the shorthand for the current directory.
      • the extension for scripts is ".sh"
      • Be careful of spacing, because it counts!!!
    2.  
    3. Make the script executable with the chmod command in the following way: chmod 700 myfirstscript.sh
    4.  
    5. Run the script - ./myfirstscript.sh yourname
    6.  
    7. open the script in nano and modify it such that in the script are commands to:
      • navigate to the subdirectory MyNewDirectory
      • list the files
      • navigate back to the parent directory
      • list the files, directories, and hidden files there.
      • List only the .txt files (use a wildcard expression in the command)
      • add a variable
        • value will be the second argument to the command to run the script.
        • label it $2.
        • choose how to use this variable. e.g. use it in the until loop (see d below) you will create or change the text echoed in the loop to use your new variable.
      • include one of the predefined variables discussed above
      • change the while loop to an until loop (google the syntax for an until loop)
      • Add an instruction at the end of the script to invoke a long listing of the current directory and output just the last 3 entries (use piping).
       
    8. Save the modified script.
    9.  
    10. Run it.

    In addition to while and until loops, for loops can be written. For loops iterate over a sequence. Scripts can be written to do many more complicated tasks. For example, a script can be written to read and display the contents of a text file. Take time to explore the ways to write and use scripts. The time invested now may save you time in the future. Some sample scripts can be found at scripts


    SUBMISSION:

    Submit a tar file (see below for instructions) that has:
    • Pdf file with screenshots or copy/paste and the required work. Use headings and subheadings to identify the tasks and subtask numbers.
    • two .sh files (the scripts)

    Tar files

    Tar files (Tape Archive files) are files that store multiple files in one single file. They have the extension .tar. If the files in the Tar file are compressed (thus making the file a smaller size than the sum of the sizes of the files in it), the extension is either tgz or tar.gz and the file is called a TGZ file or a tarball.

    How to make a compressed TAR file:

    • One can build the tarball from an entire directory, a single file or a list of files using these commands:
      • General format: tar -czvf destinationName.tar.gz source
    • The switches are:
      • -c Create an archive
      • -z Compress the archive
      • -v Display progress in the terminal (optional "verbose" mode)
      • -f Allows specifying the filename of the destination archive (tarball)

    REFERENCES
    • Hoffman, C. (2016) "How to Compress and Extract Files Using the tar Command on Linux" How-To Geek, available at https://www.howtogeek.com/248780/how-to-compress-and-extract-files-using-the-tar-command-on-linux/
    • Kim. M. (2011) "POSIX Command Line" available at http://users.ece.utexas.edu/~miryung/teaching/EE461L-Spring2012/labs/posix.html
    • SS64.com (2017) "An A-Z Index of the Bash command line for Linux" available at https://ss64.com/bash/

    Created: Plotnick and Pfaffmann

    Plotnick and Pfaffmann, Lafayette College, Last Modified: 8/26/2017