The Linux Command Line Structure 1

From Colwiki.org

Jump to: navigation, search

A basic way to interact with a computer system is to use the command line. The shell interprets the instructions typed in at the keyboard. That is the shell is the interface between a human user and the Linux Operating System. The shell prompt (ending with $ or # for user root) indicates that it is ready for user input.

You can access the Linux Shell by Pressing Ctrl+Alt+F1 or F2 or F3 or F4 or F5 or F6. These commands open up a shell terminal where you can be able to enter any Linux command. You may also access the terminal on the windows interface (Gnome Terminal on SLES – Click on Computer then Choose “More Application” then choose Gnome Terminal).This terminal runs a shell which is a programming environment which can be used to perform automated tasks. Shell programs are called scripts. The most common shells are summarized in the table below:

Image:Shells.png

Since the bash shell is one of the most widely used shells we shall concentrate on the use of this shell. This Module shall focus on the use of various Linux commands to perform basic file management commands in the Linux System. In this Module you will be:


Outcomes

Introduced to the Linux Command Structure (Variables and command options), the Interactive Shell, metacharacters and quotes plus perform the following:
  • Carry out Basic File Management Operations including creating,Deleting, Editing, Renaming, Copying etc file contents and folders
  • Moving around the file system;
  • Find files and directories; and.
  • Work with hard and soft links.



Terminologies

  • Shell: A Unix shell is a command-line interpreter (see shell) and script host that provides a traditional user interface for the Unix operating system and for Unix-like systems. Users direct the operation of the computer by entering command input as text for a command line interpreter to execute or by creating text scripts of one or more such commands.


Contents

The Interactive Shell

Shell commands are often of the form

command [options] {arguments}.

To print text to the screen the bash shell will use the echo

$echo “this is a short line” 

The shell interprets the first “word” of any string given on the command line as a command. If the string is a full or relative path to an executable then the executable is started. If the first word has no “/” characters, then the shell will scan directories defined in the PATH variable and attempt to run the first command matching the string.

For example if the PATH variable only contains the directories /bin and /usr/bin then a command stored in /etc will not be found therefore, the full path needs to be specifies.

An alternative to typing the full path to an executable is to use a relative path. For example, if the user is in the directory where a particular program is stored then one can type:

 $ ./<Program Name>

Variables

Shell variables are similar to variables used in any computing language. Variable names are limited to alphanumeric characters. For example CREDIT=300 simply assigns the value 300 to the variable named CREDIT.

Initialize a variable: Variable-Name=value (no spaces!!) Reference a variable: $Variable-Name

CREDIT=300
echo $CREDIT

Export, Set and Env

There are two types of variable: local and exported. Local variables will be accessible only to the current shell. On the other hand, exported variables are accessible by both the shell and any child process started from that shell. The commands set and env are used to list defined variables

The set and env commands

Image:Setenv.png

A global variable is global in the sense that any child process can reference it.

Image:Localexport.png


Example: Make the CREDIT variable a global variable. Test whether it's listed with set or env.

export CREDIT
env | grep CREDIT

Start a new shell (child process) and verify that CREDIT is accessible. Can one start any shell and be sure that CREDIT is still declared?

List of common predefined variables

PREDEFINED VARIABLES MEANING DISPLAY Used by X to identify where to run a client application HISTFILE Path to the users .bash_history file HOME The path to the user's home LOGNAME The name used by the user to log in PATH List of directories searched by the shell for programs to be executed when a command is entered without a path. PWD The current working directory SHELL The shell used (bash in most Linux distributions) TERM The current terminal emulation

Special variables

The next few variables are related to process management.

Image:Specialvariabls.png

Input Output Redirection

Linux processes normally open three standard file descriptors which enable it to process input and output. These standard descriptors can be redefined for any given process. In most cases the stdin descriptor is the keyboard, and the two output descriptors, stdout and stderr, is the screen.

Image:3processdescriptors.png

Numerical values for stdin, stderr and stdout

  • stdin 0
  • stdout 1
  • stderr 2

STDOUT REDIRECTION

program > file

The data flows from left to right for example

fdisk –l > partions.txt  

This will run the fdisk utility and output the result to the partitions.txt file. No output is visible. Also notice that the shell will read this line from the right. As a result, the partitions.txt file will be created first if it doesn’t exist and overwritten if the ‘>’ operator is used. The ‘>>’ operator will append output to a file.

Image:Stdoutredirection.png

STDIN REDIRECTION

program < file

In this case data flows from right to left. The ‘<’ operator is only used for stdin and cannot be used for stdout.If the file instructions contains on each line the letters p, m, and q then the next example would cause fdisk to print the partition table of /dev/hda, print the utility’s help screen and finally quit:

fdisk /dev/hda  < instructions 

Image:Stdin.png

STDERR REDIRECTION

program 2> errorfile

stdin, stdout and stderr are represented by 0, 1 and 2 respectively. This allows one to select the stderr stream:

'find / 2> /dev/null

Image:Stderr.png

PIPED COMMANDS

program1 | program2

Pipes are represented by the “|” symbol. The data stream goes from the left to the right. The next figure illustrates how the stdout for one process is redirected to the stdin for another process.

Image:Piped.png

cat /var/log/messages | less 
                     

NB Multiple output redirects are parsed from right to left, so the following commands are not equivalent.

Do-command  2>&1  >logfile
Do-command  >logfile  2>&1

Metacharacters and Quotes

Metacharacters are characters that have special meaning for the shell. They are mainly used for file globbing that is to match several files or directory names using a minimum of letters. The input (<), output (>) and pipe (|) characters are also special characters as well as the dollar ($) sign used for variables. We will not list them here but note that these characters are seldom used to name regular files.

Wildcards

  • The * wildcard can replace any number of characters.
ls  /usr/bin/b*  - Lists all programs starting with a 'b'
  • The ? wildcard replaces any one character.
ls  /usr/bin/?b*  - Lists all programs having a 'b' as the second letter
  • Ranges

[ ] is used to define a range of value.

ls  a[0-9]- Lists all files starting with an 'a' and have a digit in second position. Also
ls  [!Aa]*- Lists all files that don't start with an 'a' or an 'A'

{string1,string2}; although not just a file naming wildcard, it can be used to match the names of existing files.

ls  index.{htm,html}

Quotes and escape codes

The special meaning of metacharacters can be cancelled by escape characters, which are also metacharacters. The backslash (\) is called the escape character and cancels the meaning of all metacharacters forcing the shell to interpret them literally. The single quotes (' ') cancel the meaning of all metacharacters except the backslash.The double quotes (" ") are the weakest quotes but cancel most of the special meaning of the enclosed characters except the pipe (|), the backslash (\) and a variable ($var).

The back tick

Back quotes `` will execute a command enclosed. The next example defines the variable TIME using the date command.

$TIME="Today's date is `date +%a:%d:%b`”
$echo $TIME
$Today's date is Sun:15:Jul

Another way of executing commands (similar to the back ticks) is to use $(). This will execute the enclosed command and treat it as a variable.

TIME=$(date)

Command History

To view the list of previously typed commands you can use the bash built-in command history.

History
1	ls
2	grep   500 /etc/passwd

You can recall commands by using the Up-arrow and Down-arrow on your keyboard. There are also emacs key bindings that enable you to execute and even edit these lines.

Image:Emacs.png

The bang ! key can be used to rerun a command.

Example

!x - executes the latest command in the history list starting with an 'x'
!2 -runs command number 2 from the history output
!-2-runs the command before last
!!-runs the last command
^string1^string2-run previous command and replace string1 by string2

Other commands

Aliases

You can create aliases for commands needing many arguments. The format to create an alias is

alias myprog='command [options]{arguments}' 

Command completion

By pressing TAB, the shell will complete the commands you have started typing in. By typing alias alone at the command line you will get a list of currently defined aliases. << is a redirection for EOF. For example

$cat << stop

will accept standard input until the keyword 'stop' is entered.

Summary

Summary

In this module you learned how to work with the command shell and noted the structure of any Linus command. It is important to note that the shell is not part of the kernel but works with the kernel to execute user instructions.

You also learned how to navigate your way on the command line. It is important to learn the command line as a system administrator as you will be required to perform most of your functions within the command line.


Assignment

Type the next commands and represent the sequence of execution (if possible) using diagrams similar to the ones used in this module. Image:Assignment1.png

2. List all files in /usr/X11R6/bin that don't start with an x

	ls /usr/X11R6/bin/[!x]*

3. The command xterm has the following options:

-bg <color> - set background
-fg <color> - set foreground
-e <command> - execute ‘command’ in terminal

Set a new alias such that the su command opens a new color xterm and prompts for a root password.

	alias su=”xterm -bg orange -fg brown -e su - &” 

Where would you store this alias on the system? ___________

4. You can encode files using uuencode. The encoded file is redirected to stdout. For example: uuencode /bin/bash super-shell > uufile encodes /bin/bash and will produce a file called super-shell when running uudecode against the uufile

-Mail the uuencoded /bin/bash to a local user (for this you can either use uuencode and a pipe | , or save the uuencoded output to a file uufile and use STDIN redirection <). -Split the uuencoded file into 5 files:

uuencode /bin/bash super-shell > uufile
split –b 150000 uufile  base-name. '

This will create files called base-name.aa, base-name.ab, etc . To get a uuencoded file with all the original data (unsplit) do

cat base-name.* > uufile.new 

Finally uudecode the file and check it still works.

uudecode   uufile.new

This should create a binary file called super-shell

5. Which tool finds the full path to a binary by scanning the PATH variable? _____

Variables

1. Do the following

Assign the value ‘virus’ to the variable ALERT.

	ALERT=virus

Verify that it is defined using the set command:

	set |grep ALERT

Is ALERT listed when using env instead of set?

Next type ‘bash’. Can you access the ALERT variable?

	bash
	echo $ALERT

NOTE the value of ALERT: ______ ( is it blank?)

Type exit (or ^D) to return to your original session.

Use the export command to make ALERT a global variable.

	export ALERT

Verify that it is a global (env) variable

	env | grep ALERT

Notice that the variable VAR is referenced with $VAR. (i) Rerun this command. (ii) Rerun this command replacing CREDIT01 by $CREDIT01

3. Using appropriate quotes change your PS1 variable to include the full path to your working directory. (Hint: the value of PS1 is [\u@ \W]\$ , you only need to replace the \W by a \w)

PS1='[\u@\h \w ]\$ '

What does PS2 look like? ________

Alternative Interfaces

Download the Webmin software package for your distribution by visiting www.webmin.com. The download section is http://www.webmin.com/download.html . See to the left and follow the instructions for your distribution. Access the webmin interface by opening up your browser and visiting: http://localhost:10000/. Log in with your root username and password and evaluate the functionality of this interface for your common system administrators activities.

Image:somerights20.png This work is licenced under a Creative Commons - By Attribution Licence - Share Alike License.

Personal tools
News & Events