Linux command shell programming

What is «the Shell»?

Simply put, the shell is a program that takes commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix-like system such as Linux. Nowadays, we have graphical user interfaces (GUIs) in addition to command line interfaces (CLIs) such as the shell.

On most Linux systems a program called bash (which stands for Bourne Again SHell, an enhanced version of the original Unix shell program, sh , written by Steve Bourne) acts as the shell program. Besides bash , there are other shell programs available for Linux systems. These include: ksh , tcsh and zsh .

What’s a «Terminal?»

It’s a program called a terminal emulator. This is a program that opens a window and lets you interact with the shell. There are a bunch of different terminal emulators we can use. Some Linux distributions install several. These might include gnome-terminal , konsole , xterm , rxvt , kvt , nxterm , and eterm .

Starting a Terminal

Window managers usually have a way to launch a terminal from the menu. Look through the list of programs to see if anything looks like a terminal emulator. While there are a number of different terminal emulators, they all do the same thing. They give us access to a shell session. You will probably develop a preference for one, based on the different bells and whistles it provides.

Testing the Keyboard

OK, let’s try some typing. Bring up a terminal window. The first thing we should see is a shell prompt that contains our user name and the name of the machine followed by a dollar sign. Something like this:

Excellent! Now type some nonsense characters and press the enter key.

If all went well, we should have gotten an error message complaining that it cannot understand the command:

Wonderful! Now press the up-arrow key. Watch how our previous command «kdkjflajfks» returns. Yes, we have command history. Press the down-arrow and we get the blank line again.

Recall the «kdkjflajfks» command using the up-arrow key if needed. Now, try the left and right-arrow keys. We can position the text cursor anywhere in the command line. This allows us to easily correct mistakes.

You’re not operating as root, are you?

If the last character of your shell prompt is # rather than $, you are operating as the superuser. This means that you have administrative privileges. This can be dangerous, since you are able to delete or overwrite any file on the system. Unless you absolutely need administrative privileges, do not operate as the superuser.

Using the Mouse

Even though the shell is a command line interface, the mouse is still handy.

Besides using the mouse to scroll the contents of the terminal window, we can can use it to copy text. Drag the mouse over some text (for example, «kdkjflajfks» right here on the browser window) while holding down the left button. The text should highlight. Release the left button and move the mouse pointer to the terminal window and press the middle mouse button (alternately, press both the left and right buttons at the same time when working on a touch pad). The text we highlighted in the browser window should be copied into the command line.

A few words about focus.

When you installed your Linux system and its window manager (most likely Gnome or KDE), it was configured to behave in some ways like that legacy operating system.

In particular, it probably has its focus policy set to «click to focus.» This means that in order for a window to gain focus (become active) you have to click in the window. This is contrary to traditional X Window behavior. You should consider setting the focus policy to «focus follows mouse». You may find it strange at first that windows don’t raise to the front when they get focus (you have to click on the window to do that), but you will enjoy being able to work on more than one window at once without having the active window obscuring the other. Try it and give it a fair trial; I think you will like it. You can find this setting in the configuration tools for your window manager.

Читайте также:  Лучший wifi адаптер для windows 10 64 bit

Further Reading

  • The Wikipedia entry for Steve Bourne, developer of the original Bourne shell
  • The Wikipedia article on the Unix shell, the place where all this fun got started
  • The «Power Terminals» Adventure

© 2000-2021, William E. Shotts, Jr. Verbatim copying and distribution of this entire article is permitted in any medium, provided this copyright notice is preserved.

Linux® is a registered trademark of Linus Torvalds.

Источник

Introduction to Linux Shell and Shell Scripting

If you are using any major operating system you are indirectly interacting to shell. If you are running Ubuntu, Linux Mint or any other Linux distribution, you are interacting to shell every time you use terminal. In this article I will discuss about linux shells and shell scripting so before understanding shell scripting we have to get familiar with following terminologies –

  • Kernel
  • Shell
  • Terminal

What is Kernel

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

The kernel is a computer program that is the core of a computer’s operating system, with complete control over everything in the system. It manages following resources of the Linux system –

  • File management
  • Process management
  • I/O management
  • Memory management
  • Device management etc.
      It is often mistaken that Linus Torvalds has developed Linux OS, but actually he is only responsible for development of Linux kernel.
      Complete Linux system = Kernel + GNU system utilities and libraries + other management scripts + installation scripts.

    What is Shell

    A shell is special user program which provide an interface to user to use operating system services. Shell accept human readable commands from user and convert them into something which kernel can understand. It is a command language interpreter that execute commands read from input devices such as keyboards or from files. The shell gets started when the user logs in or start the terminal.

    Command Line Shell

    Shell can be accessed by user using a command line interface. A special program called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the human readable commands such as “cat”, “ls” etc. and then it is being execute. The result is then displayed on the terminal to the user. A terminal in Ubuntu 16.4 system looks like this –

    linux command line

    It will list all the files in current working directory in long listing format.
    Working with command line shell is bit difficult for the beginners because it’s hard to memorize so many commands. It is very powerful, it allows user to store commands in a file and execute them together. This way any repetitive task can be easily automated. These files are usually called batch files in Windows and Shell Scripts in Linux/macOS systems.

    Graphical Shells

    Graphical shells provide means for manipulating programs based on graphical user interface (GUI), by allowing for operations such as opening, closing, moving and resizing windows, as well as switching focus between windows. Window OS or Ubuntu OS can be considered as good example which provide GUI to user for interacting with program. User do not need to type in command for every actions.A typical GUI in Ubuntu system –

    There are several shells are available for Linux systems like –

    • BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as default login shell in Linux systems and in macOS. It can also be installed on Windows OS.
    • CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming language.
    • KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard specifications etc.

    Each shell does the same job but understand different commands and provide different built in functions.

    Shell Scripting

    Usually shells are interactive that mean, they accept command as input from users and execute them. However some time we want to execute a bunch of commands routinely, so we have type in all commands each time in terminal.
    As shell can also take commands as input from file we can write these commands in a file and can execute them in shell to avoid this repetitive work. These files are called Shell Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script is saved with .sh file extension eg. myscript.sh

    A shell script have syntax just like any other programming language. If you have any prior experience with any programming language like Python, C/C++ etc. it would be very easy to get started with it.
    A shell script comprises following elements –

    • Shell Keywords – if, else, break etc.
    • Shell commands – cd, ls, echo, pwd, touch etc.
    • Functions
    • Control flow – if..then..else, case and shell loops etc.

    Why do we need shell scripts

    There are many reasons to write shell scripts –

    • To avoid repetitive work and automation
    • System admins use shell scripting for routine backups
    • System monitoring
    • Adding new functionality to the shell etc.

    Advantages of shell scripts

    • The command and syntax are exactly the same as those directly entered in command line, so programmer do not need to switch to entirely different syntax
    • Writing shell scripts are much quicker
    • Quick start
    • Interactive debugging etc.

    Disadvantages of shell scripts

    • Prone to costly errors, a single mistake can change the command which might be harmful
    • Slow execution speed
    • Design flaws within the language syntax or implementation
    • Not well suited for large and complex task
    • Provide minimal data structure unlike other scripting languages. etc

    Simple demo of shell scripting using Bash Shell

    If you work on terminal, something you traverse deep down in directories. Then for coming few directories up in path we have to execute command like this as shown below to get to the “python” directory –

    Источник

    shell programming

    Introduction

    Common shell script interpreters on Unix/Linux include bash, sh, csh, ksh, etc. They are customarily called a kind of Shell. We often talk about how many kinds of shells there are, but in fact we are talking about shell script interpreters.

    1. Hello World

    Open a text editor and create a new file test.sh with the extension .sh (sh stands for shell).
    Enter some code:

    2. Notes

    Lines beginning with # are comments and will be ignored by the interpreter. There is no multi-line comment in sh, only one # sign can be added to each line.

    3. Printout

    Echo: is an internal command of Shell, used to print the specified string on the screen.
    echo arg echo -e arg #Execute the escape character in arg. Echo added -e will wrap by default echo arg> myfile #Display the result redirected to the file, will generate the myfile file
    Note that the effects of single quotes and double quotes after echo are different. Single quotes cannot escape the characters inside. Double quotation marks are optional, and single quotation marks are mainly used in the original output.
    printf: Formatted output statement. The printf command is used to format the output and is an enhanced version of the echo command. It is a limited variant of the C language printf() library function, and is slightly different in syntax.
    Like the echo command, the printf command can also output a simple string: printf “hello\n” printf does not automatically wrap like echo, you must explicitly add a newline character (\n).
    Note: printf is defined by the POSIX standard, and its portability is better than echo.

    The syntax of the printf command:

    Here is only the difference from the C language printf() function:

    • printf command without parentheses
    • The format-string can be without quotation marks, but it is best to add it. Single quotation marks and double quotation marks are acceptable.
    • When there are more parameters than the format control character (%), the format control character can be reused and all parameters can be converted.
    • The arguments are separated by spaces without commas.

    4. Define variables

    the first method
    declare -i a
    a=5+5
    echo $a

    The second method
    let b=6+6
    echo $b

    The third method
    c=$((7+7))
    echo c ( ( ) ) generation for l e t l i n u x in s h e l l change the amount c (()) instead of let shell variables in linux c ( ( ) ) generation for l e t l i n u x in s h e l l change the amount #,[email protected],$0,$1,$2 meaning interpretation

    written in the shell

    5. Operators

    • Shell operator
      Bash supports many operators, including arithmetic operators, relational operators, Boolean operators, string operators, and file test operators
      arithmetic operators
      Native bash does not support simple mathematical operations, but it can be achieved through other commands, such as awk and expr, expr is the most commonly used.
      expr is an expression calculation tool that can be used to evaluate expressions.
      Note: The symbols must be separated by spaces

    Note: true in Linux is 0, false is 1
    File test operator
    The file test operator is used to detect various attributes of Unix files.

    File test operator list Operator Description Example

    6. Strings and arrays

    String

    String is the most commonly used and most useful data type in shell programming (except for numbers and strings, there are no other types that are easy to use). Strings can be in single quotes, double quotes, or not.
    The difference between single and double quotes is similar to PHP:

    • Variables can be in double quotes, and single quotes are output as they are;
    • Escape characters can appear in double quotes, and single quotes are output as they are;
    • Single quotes cannot appear in a single quote string.
    1. Concatenated string
    1. Get string length
    1. Intercept string
    1. Find string

    Array

    Bash supports one-dimensional arrays (multidimensional arrays are not supported), and there is no limit to the size of the array. Similar to the C language, the subscripts of the array elements are numbered from 0. To obtain the elements in the array, use subscripts, which can be integers or arithmetic expressions, and their value should be greater than or equal to 0.
    In Shell, brackets are used to denote arrays, and array elements are separated by spaces. The general form of defining an array is: array_name=(value1 value2 . valuen)
    For example: array_name=(value0 value1 value2 value3) Or array_name=( value0 value1 value2 value3 )
    You can also define each component of the array separately: array_name[0]=value0 array_name[1]=value1 array_name[2]=value2
    does not need to use continuous subscripts, and the range of subscripts is unlimited.
    Read the array:

    7. Condition control

    1. Conditional judgment: if statement

    The if… else statement can also be written in one line and run as a command
    a=10;b=20;if [ $a == $b ];then echo «a is equal to b»;else echo «a is not equal to b»;fi;

    2. Branch control: case statement

    case… esac is similar to the switch… case statement in other languages ​​and is a multi-branch selection structure.
    Example:

    3. Loop statement

    1. while loop

    As long as the conditions behind while are met, the code block in do is always executed.
    Example:

    2. until loop

    The until loop executes a series of commands until the condition is true and stops. The until loop and the while loop are handled in the opposite way. Generally the while loop is better than the until loop, but in some cases, and only in rare cases, the until loop is more useful.
    Example:

    -gt means greater than, the loop will only end when sum is greater than 10

    3. for loop

    The shell’s for loop is different from languages ​​such as c and php, and is very similar to Python. The following is the syntax format:
    for variable in list do command1 command2 . commandN done
    Example:

    Traverse the files in the directory:

    Traverse the contents of the file:
    cal 2020 >> cal.txt

    Print nine-nine multiplication table

    4. Break out of the loop

    In the loop process, sometimes it is necessary to force a break out of the loop when the loop end condition is not reached. Like most programming languages, Shell also uses break and continue to break out of the loop.
    break
    The break command allows jumping out of all loops (terminating execution of all subsequent loops).
    ;; Can also be expressed as break
    continue
    The continue command is similar to the break command, with only one difference. It will not jump out of all loops, only the current loop.

    8. Function

    Function allows us to divide a complex function into several modules, making the program structure clearer and the code repetition rate higher. Like other programming languages, Shell also supports functions. Shell functions must be defined before use.

    1. Function definition
      The definition format of the Shell function is as follows:
    1. Function call

    The return value of the Shell function can only be an integer, which is generally used to indicate whether the function is executed successfully or not, 0 indicates success, and other values ​​indicate failure. If you return other data, such as a string, you will often get an error message: numeric argument required.
    If you must let the function return a string, you can first define a variable to receive the calculation result of the function. The script accesses this variable when needed to obtain the function return value.

    Источник

    Читайте также:  Aspire one загрузочный диск windows
Оцените статью