Сценарии оболочки это

This article is about scripting in Unix-like systems. For batch programming in DOS, OS/2 and Windows, see Batch file. For batch programming in Windows PowerShell shell, see Windows PowerShell § Scripting. For programming in the shells (cmd.exe) in operating systems of the Windows NT/2000 series, see cmd.exe. For shell programming, by means of files called Command Scripts or Procedures on Vax/VMS machines, see DIGITAL Command Language.

This article is about scripting in Unix-like systems. For batch programming in DOS, OS/2 and Windows, see Batch file. For batch programming in Windows PowerShell shell, see Windows PowerShell § Scripting. For programming in the shells (cmd.exe) in operating systems of the Windows NT/2000 series, see cmd.exe. For shell programming, by means of files called Command Scripts or Procedures on Vax/VMS machines, see DIGITAL Command Language.

A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter.[1] The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script which sets up the environment, runs the program, and does any necessary cleanup or logging, is called a wrapper.

The term is also used more generally to mean the automated mode of running an operating system shell; each operating system uses a particular name for these functions including batch files (MSDos-Win95 stream, OS/2), command procedures (VMS), and shell scripts (Windows NT stream and third-party derivatives like 4NT—article is at cmd.exe), and mainframe operating systems are associated with a number of terms.

Shells commonly present in Unix and Unix-like systems include the Korn shell, the Bourne shell, and GNU Bash. While a Unix operating system may have a different default shell, such as Zsh on macOS, these shells are typically present for backwards compatibility.

Capabilities[edit]

[edit]

Comments are ignored by the shell. They typically begin with the hash symbol (#), and continue until the end of the line.[2]

Configurable choice of scripting language[edit]

The shebang, or hash-bang, is a special kind of comment which the system uses to determine what interpreter to use to execute the file. The shebang must be the first line of the file, and start with «#!«.[2] In Unix-like operating systems, the characters following the «#!» prefix are interpreted as a path to an executable program that will interpret the script.[3]

Shortcuts[edit]

A shell script can provide a convenient variation of a system command where special environment settings, command options, or post-processing apply automatically, but in a way that allows the new script to still act as a fully normal Unix command.

One example would be to create a version of ls, the command to list files, giving it a shorter command name of l, which would be normally saved in a user’s bin directory as /home/username/bin/l, and a default set of command options pre-supplied.

#!/bin/sh
LC_COLLATE=C ls -FCas "$@"

Here, the first line uses a shebang to indicate which interpreter should execute the rest of the script, and the second line makes a listing with options for file format indicators, columns, all files (none omitted), and a size in blocks. The LC_COLLATE=C sets the default collation order to not fold upper and lower case together, not intermix dotfiles with normal filenames as a side effect of ignoring punctuation in the names (dotfiles are usually only shown if an option like -a is used), and the "$@" causes any parameters given to l to pass through as parameters to ls, so that all of the normal options and other syntax known to ls can still be used.

The user could then simply use l for the most commonly used short listing.

Another example of a shell script that could be used as a shortcut would be to print a list of all the files and directories within a given directory.

In this case, the shell script would start with its normal starting line of #!/bin/sh. Following this, the script executes the command clear which clears the terminal of all text before going to the next line. The following line provides the main function of the script. The ls -al command lists the files and directories that are in the directory from which the script is being run. The ls command attributes could be changed to reflect the needs of the user.

Note: If an implementation does not have the clear command, try using the clr command instead.

Batch jobs[edit]

Shell scripts allow several commands that would be entered manually at a command-line interface to be executed automatically, and without having to wait for a user to trigger each stage of the sequence. For example, in a directory with three C source code files, rather than manually running the four commands required to build the final program from them, one could instead create a script for POSIX-compliant shells, here named build and kept in the directory with them, which would compile them automatically:

#!/bin/sh
printf 'compiling...n'
cc -c foo.c
cc -c bar.c
cc -c qux.c
cc -o myprog foo.o bar.o qux.o
printf 'done.n'

The script would allow a user to save the file being edited, pause the editor, and then just run ./build to create the updated program, test it, and then return to the editor. Since the 1980s or so, however, scripts of this type have been replaced with utilities like make which are specialized for building programs.

Generalization[edit]

Simple batch jobs are not unusual for isolated tasks, but using shell loops, tests, and variables provides much more flexibility to users. A POSIX sh script to convert JPEG images to PNG images, where the image names are provided on the command-line—possibly via wildcards—instead of each being listed within the script, can be created with this file, typically saved in a file like /home/username/bin/jpg2png

#!/bin/sh
for jpg; do                                  # use $jpg in place of each filename given, in turn
    png=${jpg%.jpg}.png                      # construct the PNG version of the filename by replacing .jpg with .png
    printf 'converting "%s" ...n' "$jpg"    # output status info to the user running the script
    if convert "$jpg" jpg.to.png; then       # use convert (provided by ImageMagick) to create the PNG in a temp file
        mv jpg.to.png "$png"                 # if it worked, rename the temporary PNG image to the correct name
    else                                     # ...otherwise complain and exit from the script
        printf >&2 'jpg2png: error: failed output saved in "jpg.to.png".n'
        exit 1
    fi                                       # the end of the "if" test construct
done                                         # the end of the "for" loop
printf 'all conversions successfuln'        # tell the user the good news

The jpg2png command can then be run on an entire directory full of JPEG images with just /home/username/bin/jpg2png *.jpg

Programming[edit]

Many modern shells also supply various features usually found only in more sophisticated general-purpose programming languages, such as control-flow constructs, variables, comments, arrays, subroutines and so on. With these sorts of features available, it is possible to write reasonably sophisticated applications as shell scripts. However, they are still limited by the fact that most shell languages have little or no support for data typing systems, classes, threading, complex math, and other common full language features, and are also generally much slower than compiled code or interpreted languages written with speed as a performance goal.

The standard Unix tools sed and awk provide extra capabilities for shell programming; Perl can also be embedded in shell scripts as can other scripting languages like Tcl. Perl and Tcl come with graphics toolkits as well.

Typical POSIX scripting languages[edit]

Scripting languages commonly found on UNIX, Linux, and POSIX-compliant operating system installations include:

  • KornShell (ksh) in several possible versions such as ksh88, Korn Shell ’93 and others.
  • The Bourne shell (sh), one of the oldest shells still common in use
  • The C shell (csh)
  • GNU Bash (bash)
  • tclsh, a shell which is a main component of the Tcl/Tk programming language.
  • The wish is a GUI-based Tcl/Tk shell.

The C and Tcl shells have syntax quite similar to that of said programming languages, and the Korn shells and Bash are developments of the Bourne shell, which is based on the ALGOL language with elements of a number of others added as well.[4] On the other hand, the various shells plus tools like awk, sed, grep, and BASIC, Lisp, C and so forth contributed to the Perl programming language.[5]

Other shells that may be available on a machine or for download and/or purchase include:

  • Almquist shell (ash)
  • PowerShell (msh)
  • Z shell (zsh, a particularly common enhanced KornShell)
  • The Tenex C Shell (tcsh).

Related programs such as shells based on Python, Ruby, C, Java, Perl, Pascal, Rexx etc. in various forms are also widely available. Another somewhat common shell is Old shell (osh), whose manual page states it «is an enhanced, backward-compatible port of the standard command interpreter from Sixth Edition UNIX.»[6]

So called remote shells such as

  • a Remote Shell (rsh)
  • a Secure Shell (ssh)

are really just tools to run a more complex shell on a remote system and have no ‘shell’ like characteristics themselves.

Other scripting languages[edit]

Many powerful scripting languages have been introduced for tasks that are too large or complex to be comfortably handled with ordinary shell scripts, but for which the advantages of a script are desirable and the development overhead of a full-blown, compiled programming language would be disadvantageous. The specifics of what separates scripting languages from high-level programming languages is a frequent source of debate, but, generally speaking, a scripting language is one which requires an interpreter.

Life cycle[edit]

Shell scripts often serve as an initial stage in software development, and are often subject to conversion later to a different underlying implementation, most commonly being converted to Perl, Python, or C. The interpreter directive allows the implementation detail to be fully hidden inside the script, rather than being exposed as a filename extension, and provides for seamless reimplementation in different languages with no impact on end users.

While files with the «.sh» file extension are usually a shell script of some kind, most shell scripts do not have any filename extension.[7][8][9][10]

Advantages and disadvantages[edit]

Perhaps the biggest advantage of writing a shell script is that the commands and syntax are exactly the same as those directly entered at the command-line. The programmer does not have to switch to a totally different syntax, as they would if the script were written in a different language, or if a compiled language were used.

Often, writing a shell script is much quicker than writing the equivalent code in other programming languages. The many advantages include easy program or file selection, quick start, and interactive debugging. A shell script can be used to provide a sequencing and decision-making linkage around existing programs, and for moderately sized scripts the absence of a compilation step is an advantage. Interpretive running makes it easy to write debugging code into a script and re-run it to detect and fix bugs. Non-expert users can use scripting to tailor the behavior of programs, and shell scripting provides some limited scope for multiprocessing.

On the other hand, shell scripting is prone to costly errors. Inadvertent typing errors such as rm -rf * / (instead of the intended rm -rf */) are folklore in the Unix community; a single extra space converts the command from one that deletes all subdirectories contained in the current directory, to one which deletes everything from the file system’s root directory. Similar problems can transform cp and mv into dangerous weapons, and misuse of the > redirect can delete the contents of a file. This is made more problematic by the fact that many UNIX commands differ in name by only one letter: cp, cd, dd, df, etc.

Another significant disadvantage is the slow execution speed and the need to launch a new process for almost every shell command executed. When a script’s job can be accomplished by setting up a pipeline in which efficient filter commands perform most of the work, the slowdown is mitigated, but a complex script is typically several orders of magnitude slower than a conventional compiled program that performs an equivalent task.

There are also compatibility problems between different platforms. Larry Wall, creator of Perl, famously wrote that «It is easier to port a shell than a shell script.»[11]

Similarly, more complex scripts can run into the limitations of the shell scripting language itself; the limits make it difficult to write quality code, and extensions by various shells to ameliorate problems with the original shell language can make problems worse.[12]

Many disadvantages of using some script languages are caused by design flaws within the language syntax or implementation, and are not necessarily imposed by the use of a text-based command-line; there are a number of shells which use other shell programming languages or even full-fledged languages like Scsh (which uses Scheme).

Interoperability among scripting languages[edit]

Different scripting languages may share many common elements, largely due to being POSIX based, and some shells offer modes to emulate different shells. This allows a shell script written in one scripting language to be adapted into another.

One example of this is Bash, which offers the same grammar and syntax as the Bourne shell, and which also provides a POSIX-compliant mode.[13] As such, most shell scripts written for the Bourne shell can be run in BASH, but the reverse may not be true since BASH has extensions which are not present in the Bourne shell. As such, these features are known as bashisms.[14]

Shell scripting on other operating systems[edit]

Interoperability software such as Cygwin, the MKS Toolkit, Interix (which is available in the Microsoft Windows Services for UNIX), Hamilton C shell, UWIN (AT&T Unix for Windows) and others allow Unix shell programs to be run on machines running Windows NT and its successors, with some loss of functionality on the MS-DOS-Windows 95 branch, as well as earlier MKS Toolkit versions for OS/2. At least three DCL implementations for Windows type operating systems—in addition to XLNT, a multiple-use scripting language package which is used with the command shell, Windows Script Host and CGI programming—are available for these systems as well. Mac OS X and subsequent are Unix-like as well.[15]

In addition to the aforementioned tools, some POSIX and OS/2 functionality can be used with the corresponding environmental subsystems of the Windows NT operating system series up to Windows 2000 as well. A third, 16-bit subsystem often called the MS-DOS subsystem uses the Command.com provided with these operating systems to run the aforementioned MS-DOS batch files.[16]

The console alternatives 4DOS, 4OS2, FreeDOS, Peter Norton’s NDOS and 4NT / Take Command which add functionality to the Windows NT-style cmd.exe, MS-DOS/Windows 95 batch files (run by Command.com), OS/2’s cmd.exe, and 4NT respectively are similar to the shells that they enhance and are more integrated with the Windows Script Host, which comes with three pre-installed engines, VBScript, JScript, and VBA and to which numerous third-party engines can be added, with Rexx, Perl, Python, Ruby, and Tcl having pre-defined functions in 4NT and related programs. PC DOS is quite similar to MS-DOS, whilst DR DOS is more different. Earlier versions of Windows NT are able to run contemporary versions of 4OS2 by the OS/2 subsystem.

Scripting languages are, by definition, able to be extended; for example, a MS-DOS/Windows 95/98 and Windows NT type systems allows for shell/batch programs to call tools like KiXtart, QBasic, various BASIC, Rexx, Perl, and Python implementations, the Windows Script Host and its installed engines. On Unix and other POSIX-compliant systems, awk and sed are used to extend the string and numeric processing ability of shell scripts. Tcl, Perl, Rexx, and Python have graphics toolkits and can be used to code functions and procedures for shell scripts which pose a speed bottleneck (C, Fortran, assembly language &c are much faster still) and to add functionality not available in the shell language such as sockets and other connectivity functions, heavy-duty text processing, working with numbers if the calling script does not have those abilities, self-writing and self-modifying code, techniques like recursion, direct memory access, various types of sorting and more, which are difficult or impossible in the main script, and so on. Visual Basic for Applications and VBScript can be used to control and communicate with such things as spreadsheets, databases, scriptable programs of all types, telecommunications software, development tools, graphics tools and other software which can be accessed through the Component Object Model.

See also[edit]

  • Glue code
  • Interpreter directive
  • Shebang symbol (#!)
  • Unix shells
  • PowerShell
  • Windows Script Host

References[edit]

  1. ^ Kernighan, Brian W.; Pike, Rob (1984), «3. Using the Shell», The UNIX Programming Environment, Prentice Hall, Inc., p. 94, ISBN 0-13-937699-2, The shell is actually a programming language: it has variables, loops, decision-making, and so on.
  2. ^ a b Johnson, Chris (2009).
    [1] Pro Bash Programming: Scripting the Linux Shell, Apress, Retrieved on September 27, 2019. ISBN 9781430219989
  3. ^ «exec(3p) – POSIX Programmer’s Manual». Retrieved 2020-07-24.
  4. ^ Unix Shells By Example, pp 7-10,
  5. ^ Programming Perl, 5th Edition, preface
  6. ^ «osh — manned.org». manned.org. Retrieved 2019-01-16.
  7. ^ Robbins, Arnold; Hannah, Elbert; Lamb, Linda (2008). Learning the vi and Vim Editors. p. 205. ISBN 9781449313258.
  8. ^ Easttom, Chuck (2012). Essential Linux Administration:: A Comprehensive Guide for Beginners. p. 228. ISBN 978-1435459571.
  9. ^ Kumari, Sinny (November 23, 2015). Linux Shell Scripting Essentials. Packt Publishing Ltd. ISBN 9781783552375. Retrieved May 7, 2017. Rather than using a file extension for shell scripts, it’s preferred to keep a filename without extension and let an interpreter identify the type by looking into shebang(#!).
  10. ^ Taylor, Dave; Perry, Brandon (December 16, 2016). Wicked Cool Shell Scripts, 2nd Edition: 101 Scripts for Linux, OS X and UNIX Systems. No Starch Press. ISBN 9781593276027. Retrieved May 7, 2017. Shell scripts don’t need a special file extension, so leave the extension blank (or you can add the extension .sh if you prefer, but this isn’t required.
  11. ^ Larry Wall (January 4, 1991). «Finding the last arg». Newsgroup: comp.unix.shell. Retrieved January 5, 2023.
  12. ^ Christiansen, Tom. «Csh Programming Considered Harmful».
  13. ^ «Major Differences From The Bourne Shell».
  14. ^ «24 Bashism To Avoid for POSIX-Compliant Shell Scripts». 18 May 2022.
  15. ^ MSDN[not specific enough to verify]
  16. ^ Windows NT 4 Workstation Resource Kit

External links[edit]

  • An Introduction To Shell Programming by Greg Goebel
  • UNIX / Linux shell scripting tutorial by Steve Parker
  • Shell Scripting Primer (Apple)
  • What to watch out for when writing portable shell scripts by Peter Seebach
  • Free Unix Shell scripting books
  • Beginners/BashScripting, Ubuntu Linux

This article is about scripting in Unix-like systems. For batch programming in DOS, OS/2 and Windows, see Batch file. For batch programming in Windows PowerShell shell, see Windows PowerShell § Scripting. For programming in the shells (cmd.exe) in operating systems of the Windows NT/2000 series, see cmd.exe. For shell programming, by means of files called Command Scripts or Procedures on Vax/VMS machines, see DIGITAL Command Language.

A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter.[1] The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manipulation, program execution, and printing text. A script which sets up the environment, runs the program, and does any necessary cleanup or logging, is called a wrapper.

The term is also used more generally to mean the automated mode of running an operating system shell; each operating system uses a particular name for these functions including batch files (MSDos-Win95 stream, OS/2), command procedures (VMS), and shell scripts (Windows NT stream and third-party derivatives like 4NT—article is at cmd.exe), and mainframe operating systems are associated with a number of terms.

Shells commonly present in Unix and Unix-like systems include the Korn shell, the Bourne shell, and GNU Bash. While a Unix operating system may have a different default shell, such as Zsh on macOS, these shells are typically present for backwards compatibility.

Capabilities[edit]

[edit]

Comments are ignored by the shell. They typically begin with the hash symbol (#), and continue until the end of the line.[2]

Configurable choice of scripting language[edit]

The shebang, or hash-bang, is a special kind of comment which the system uses to determine what interpreter to use to execute the file. The shebang must be the first line of the file, and start with «#!«.[2] In Unix-like operating systems, the characters following the «#!» prefix are interpreted as a path to an executable program that will interpret the script.[3]

Shortcuts[edit]

A shell script can provide a convenient variation of a system command where special environment settings, command options, or post-processing apply automatically, but in a way that allows the new script to still act as a fully normal Unix command.

One example would be to create a version of ls, the command to list files, giving it a shorter command name of l, which would be normally saved in a user’s bin directory as /home/username/bin/l, and a default set of command options pre-supplied.

#!/bin/sh
LC_COLLATE=C ls -FCas "$@"

Here, the first line uses a shebang to indicate which interpreter should execute the rest of the script, and the second line makes a listing with options for file format indicators, columns, all files (none omitted), and a size in blocks. The LC_COLLATE=C sets the default collation order to not fold upper and lower case together, not intermix dotfiles with normal filenames as a side effect of ignoring punctuation in the names (dotfiles are usually only shown if an option like -a is used), and the "$@" causes any parameters given to l to pass through as parameters to ls, so that all of the normal options and other syntax known to ls can still be used.

The user could then simply use l for the most commonly used short listing.

Another example of a shell script that could be used as a shortcut would be to print a list of all the files and directories within a given directory.

In this case, the shell script would start with its normal starting line of #!/bin/sh. Following this, the script executes the command clear which clears the terminal of all text before going to the next line. The following line provides the main function of the script. The ls -al command lists the files and directories that are in the directory from which the script is being run. The ls command attributes could be changed to reflect the needs of the user.

Note: If an implementation does not have the clear command, try using the clr command instead.

Batch jobs[edit]

Shell scripts allow several commands that would be entered manually at a command-line interface to be executed automatically, and without having to wait for a user to trigger each stage of the sequence. For example, in a directory with three C source code files, rather than manually running the four commands required to build the final program from them, one could instead create a script for POSIX-compliant shells, here named build and kept in the directory with them, which would compile them automatically:

#!/bin/sh
printf 'compiling...n'
cc -c foo.c
cc -c bar.c
cc -c qux.c
cc -o myprog foo.o bar.o qux.o
printf 'done.n'

The script would allow a user to save the file being edited, pause the editor, and then just run ./build to create the updated program, test it, and then return to the editor. Since the 1980s or so, however, scripts of this type have been replaced with utilities like make which are specialized for building programs.

Generalization[edit]

Simple batch jobs are not unusual for isolated tasks, but using shell loops, tests, and variables provides much more flexibility to users. A POSIX sh script to convert JPEG images to PNG images, where the image names are provided on the command-line—possibly via wildcards—instead of each being listed within the script, can be created with this file, typically saved in a file like /home/username/bin/jpg2png

#!/bin/sh
for jpg; do                                  # use $jpg in place of each filename given, in turn
    png=${jpg%.jpg}.png                      # construct the PNG version of the filename by replacing .jpg with .png
    printf 'converting "%s" ...n' "$jpg"    # output status info to the user running the script
    if convert "$jpg" jpg.to.png; then       # use convert (provided by ImageMagick) to create the PNG in a temp file
        mv jpg.to.png "$png"                 # if it worked, rename the temporary PNG image to the correct name
    else                                     # ...otherwise complain and exit from the script
        printf >&2 'jpg2png: error: failed output saved in "jpg.to.png".n'
        exit 1
    fi                                       # the end of the "if" test construct
done                                         # the end of the "for" loop
printf 'all conversions successfuln'        # tell the user the good news

The jpg2png command can then be run on an entire directory full of JPEG images with just /home/username/bin/jpg2png *.jpg

Programming[edit]

Many modern shells also supply various features usually found only in more sophisticated general-purpose programming languages, such as control-flow constructs, variables, comments, arrays, subroutines and so on. With these sorts of features available, it is possible to write reasonably sophisticated applications as shell scripts. However, they are still limited by the fact that most shell languages have little or no support for data typing systems, classes, threading, complex math, and other common full language features, and are also generally much slower than compiled code or interpreted languages written with speed as a performance goal.

The standard Unix tools sed and awk provide extra capabilities for shell programming; Perl can also be embedded in shell scripts as can other scripting languages like Tcl. Perl and Tcl come with graphics toolkits as well.

Typical POSIX scripting languages[edit]

Scripting languages commonly found on UNIX, Linux, and POSIX-compliant operating system installations include:

  • KornShell (ksh) in several possible versions such as ksh88, Korn Shell ’93 and others.
  • The Bourne shell (sh), one of the oldest shells still common in use
  • The C shell (csh)
  • GNU Bash (bash)
  • tclsh, a shell which is a main component of the Tcl/Tk programming language.
  • The wish is a GUI-based Tcl/Tk shell.

The C and Tcl shells have syntax quite similar to that of said programming languages, and the Korn shells and Bash are developments of the Bourne shell, which is based on the ALGOL language with elements of a number of others added as well.[4] On the other hand, the various shells plus tools like awk, sed, grep, and BASIC, Lisp, C and so forth contributed to the Perl programming language.[5]

Other shells that may be available on a machine or for download and/or purchase include:

  • Almquist shell (ash)
  • PowerShell (msh)
  • Z shell (zsh, a particularly common enhanced KornShell)
  • The Tenex C Shell (tcsh).

Related programs such as shells based on Python, Ruby, C, Java, Perl, Pascal, Rexx etc. in various forms are also widely available. Another somewhat common shell is Old shell (osh), whose manual page states it «is an enhanced, backward-compatible port of the standard command interpreter from Sixth Edition UNIX.»[6]

So called remote shells such as

  • a Remote Shell (rsh)
  • a Secure Shell (ssh)

are really just tools to run a more complex shell on a remote system and have no ‘shell’ like characteristics themselves.

Other scripting languages[edit]

Many powerful scripting languages have been introduced for tasks that are too large or complex to be comfortably handled with ordinary shell scripts, but for which the advantages of a script are desirable and the development overhead of a full-blown, compiled programming language would be disadvantageous. The specifics of what separates scripting languages from high-level programming languages is a frequent source of debate, but, generally speaking, a scripting language is one which requires an interpreter.

Life cycle[edit]

Shell scripts often serve as an initial stage in software development, and are often subject to conversion later to a different underlying implementation, most commonly being converted to Perl, Python, or C. The interpreter directive allows the implementation detail to be fully hidden inside the script, rather than being exposed as a filename extension, and provides for seamless reimplementation in different languages with no impact on end users.

While files with the «.sh» file extension are usually a shell script of some kind, most shell scripts do not have any filename extension.[7][8][9][10]

Advantages and disadvantages[edit]

Perhaps the biggest advantage of writing a shell script is that the commands and syntax are exactly the same as those directly entered at the command-line. The programmer does not have to switch to a totally different syntax, as they would if the script were written in a different language, or if a compiled language were used.

Often, writing a shell script is much quicker than writing the equivalent code in other programming languages. The many advantages include easy program or file selection, quick start, and interactive debugging. A shell script can be used to provide a sequencing and decision-making linkage around existing programs, and for moderately sized scripts the absence of a compilation step is an advantage. Interpretive running makes it easy to write debugging code into a script and re-run it to detect and fix bugs. Non-expert users can use scripting to tailor the behavior of programs, and shell scripting provides some limited scope for multiprocessing.

On the other hand, shell scripting is prone to costly errors. Inadvertent typing errors such as rm -rf * / (instead of the intended rm -rf */) are folklore in the Unix community; a single extra space converts the command from one that deletes all subdirectories contained in the current directory, to one which deletes everything from the file system’s root directory. Similar problems can transform cp and mv into dangerous weapons, and misuse of the > redirect can delete the contents of a file. This is made more problematic by the fact that many UNIX commands differ in name by only one letter: cp, cd, dd, df, etc.

Another significant disadvantage is the slow execution speed and the need to launch a new process for almost every shell command executed. When a script’s job can be accomplished by setting up a pipeline in which efficient filter commands perform most of the work, the slowdown is mitigated, but a complex script is typically several orders of magnitude slower than a conventional compiled program that performs an equivalent task.

There are also compatibility problems between different platforms. Larry Wall, creator of Perl, famously wrote that «It is easier to port a shell than a shell script.»[11]

Similarly, more complex scripts can run into the limitations of the shell scripting language itself; the limits make it difficult to write quality code, and extensions by various shells to ameliorate problems with the original shell language can make problems worse.[12]

Many disadvantages of using some script languages are caused by design flaws within the language syntax or implementation, and are not necessarily imposed by the use of a text-based command-line; there are a number of shells which use other shell programming languages or even full-fledged languages like Scsh (which uses Scheme).

Interoperability among scripting languages[edit]

Different scripting languages may share many common elements, largely due to being POSIX based, and some shells offer modes to emulate different shells. This allows a shell script written in one scripting language to be adapted into another.

One example of this is Bash, which offers the same grammar and syntax as the Bourne shell, and which also provides a POSIX-compliant mode.[13] As such, most shell scripts written for the Bourne shell can be run in BASH, but the reverse may not be true since BASH has extensions which are not present in the Bourne shell. As such, these features are known as bashisms.[14]

Shell scripting on other operating systems[edit]

Interoperability software such as Cygwin, the MKS Toolkit, Interix (which is available in the Microsoft Windows Services for UNIX), Hamilton C shell, UWIN (AT&T Unix for Windows) and others allow Unix shell programs to be run on machines running Windows NT and its successors, with some loss of functionality on the MS-DOS-Windows 95 branch, as well as earlier MKS Toolkit versions for OS/2. At least three DCL implementations for Windows type operating systems—in addition to XLNT, a multiple-use scripting language package which is used with the command shell, Windows Script Host and CGI programming—are available for these systems as well. Mac OS X and subsequent are Unix-like as well.[15]

In addition to the aforementioned tools, some POSIX and OS/2 functionality can be used with the corresponding environmental subsystems of the Windows NT operating system series up to Windows 2000 as well. A third, 16-bit subsystem often called the MS-DOS subsystem uses the Command.com provided with these operating systems to run the aforementioned MS-DOS batch files.[16]

The console alternatives 4DOS, 4OS2, FreeDOS, Peter Norton’s NDOS and 4NT / Take Command which add functionality to the Windows NT-style cmd.exe, MS-DOS/Windows 95 batch files (run by Command.com), OS/2’s cmd.exe, and 4NT respectively are similar to the shells that they enhance and are more integrated with the Windows Script Host, which comes with three pre-installed engines, VBScript, JScript, and VBA and to which numerous third-party engines can be added, with Rexx, Perl, Python, Ruby, and Tcl having pre-defined functions in 4NT and related programs. PC DOS is quite similar to MS-DOS, whilst DR DOS is more different. Earlier versions of Windows NT are able to run contemporary versions of 4OS2 by the OS/2 subsystem.

Scripting languages are, by definition, able to be extended; for example, a MS-DOS/Windows 95/98 and Windows NT type systems allows for shell/batch programs to call tools like KiXtart, QBasic, various BASIC, Rexx, Perl, and Python implementations, the Windows Script Host and its installed engines. On Unix and other POSIX-compliant systems, awk and sed are used to extend the string and numeric processing ability of shell scripts. Tcl, Perl, Rexx, and Python have graphics toolkits and can be used to code functions and procedures for shell scripts which pose a speed bottleneck (C, Fortran, assembly language &c are much faster still) and to add functionality not available in the shell language such as sockets and other connectivity functions, heavy-duty text processing, working with numbers if the calling script does not have those abilities, self-writing and self-modifying code, techniques like recursion, direct memory access, various types of sorting and more, which are difficult or impossible in the main script, and so on. Visual Basic for Applications and VBScript can be used to control and communicate with such things as spreadsheets, databases, scriptable programs of all types, telecommunications software, development tools, graphics tools and other software which can be accessed through the Component Object Model.

See also[edit]

  • Glue code
  • Interpreter directive
  • Shebang symbol (#!)
  • Unix shells
  • PowerShell
  • Windows Script Host

References[edit]

  1. ^ Kernighan, Brian W.; Pike, Rob (1984), «3. Using the Shell», The UNIX Programming Environment, Prentice Hall, Inc., p. 94, ISBN 0-13-937699-2, The shell is actually a programming language: it has variables, loops, decision-making, and so on.
  2. ^ a b Johnson, Chris (2009).
    [1] Pro Bash Programming: Scripting the Linux Shell, Apress, Retrieved on September 27, 2019. ISBN 9781430219989
  3. ^ «exec(3p) – POSIX Programmer’s Manual». Retrieved 2020-07-24.
  4. ^ Unix Shells By Example, pp 7-10,
  5. ^ Programming Perl, 5th Edition, preface
  6. ^ «osh — manned.org». manned.org. Retrieved 2019-01-16.
  7. ^ Robbins, Arnold; Hannah, Elbert; Lamb, Linda (2008). Learning the vi and Vim Editors. p. 205. ISBN 9781449313258.
  8. ^ Easttom, Chuck (2012). Essential Linux Administration:: A Comprehensive Guide for Beginners. p. 228. ISBN 978-1435459571.
  9. ^ Kumari, Sinny (November 23, 2015). Linux Shell Scripting Essentials. Packt Publishing Ltd. ISBN 9781783552375. Retrieved May 7, 2017. Rather than using a file extension for shell scripts, it’s preferred to keep a filename without extension and let an interpreter identify the type by looking into shebang(#!).
  10. ^ Taylor, Dave; Perry, Brandon (December 16, 2016). Wicked Cool Shell Scripts, 2nd Edition: 101 Scripts for Linux, OS X and UNIX Systems. No Starch Press. ISBN 9781593276027. Retrieved May 7, 2017. Shell scripts don’t need a special file extension, so leave the extension blank (or you can add the extension .sh if you prefer, but this isn’t required.
  11. ^ Larry Wall (January 4, 1991). «Finding the last arg». Newsgroup: comp.unix.shell. Retrieved January 5, 2023.
  12. ^ Christiansen, Tom. «Csh Programming Considered Harmful».
  13. ^ «Major Differences From The Bourne Shell».
  14. ^ «24 Bashism To Avoid for POSIX-Compliant Shell Scripts». 18 May 2022.
  15. ^ MSDN[not specific enough to verify]
  16. ^ Windows NT 4 Workstation Resource Kit

External links[edit]

  • An Introduction To Shell Programming by Greg Goebel
  • UNIX / Linux shell scripting tutorial by Steve Parker
  • Shell Scripting Primer (Apple)
  • What to watch out for when writing portable shell scripts by Peter Seebach
  • Free Unix Shell scripting books
  • Beginners/BashScripting, Ubuntu Linux

Сценарии оболочки

Взаимодействие пользователя с операционной
системой осуществляется через оболочку.
Оболочка (shell) –
это программа, обрабатывающая команды,
вводимые пользователем или содержащиеся
в файле (при этом файл называется
сценарием и является интерпретируемой
программой). Аналогами оболочки в среде
Windows являются командный
процессор command.com
или cmd.exe, а
аналогами сценариев – командные файлы
(bat-файлы). В Linux
существует ряд различных оболочек
(например, sh, ksh,
csh, yacc),
наиболее популярной из которых является
bash.

Сразу после запуска оболочки производится
её инициализация для установки ряда
параметров. При этом оболочкой производится
чтение двух файлов: /etc/profile
и ~/.profile.
В первом из них содержатся настройки
параметров, общие для всех пользователей.
Во втором файле каждый пользователь
может разместить свои собственные
настройки для работы с оболочкой.

Пользовательская оболочка может быть
запущена на выполнение в двух режимах
– интерактивном и не интерактивном.
Когда оболочка выдаёт пользователю
приглашение, она работает в интерактивном
режиме. Это означает, что оболочка
принимает ввод от пользователя и
выполняет команды, которые пользователь
укажет. Оболочка называется интерактивной,
поскольку она взаимодействует с
пользователем. Завершение работы с
оболочкой в этом случае происходит по
команде пользователя.

В неинтерактивном режиме оболочка
не взаимодействует с пользователем.
Вместо этого она читает команды из
некоторого файла и выполняет их. Когда
будет достигнут конец файла, оболочка
завершит свое выполнение. Запуск оболочки
в неинтерактивном режиме можно осуществить
следующим способом:

имя_оболочки
имя_файла

Здесь имя_файла
– имя файла, содержащего команды
для выполнения. Такой файл называется
сценарием оболочки. Он является
текстовым файлом и может быть создан
любым доступным текстовым редактором.

В качестве имени_оболочки
может выступать, например, sh,
bash
или имя любой другой оболочки.

Запуск сценария

Пользователю может представлять
неудобство каждый раз указывать имя
программы-оболочки для выполнения
сценария. Для того чтобы иметь возможность
выполнять сценарий, набирая только его
имя, прежде всего необходимо сделать
его исполняемым. Для этого необходимо
установить соответствующие права
доступа к файлу с помощью команды:

chmod
+x имя_файла

Кроме этого, необходимо явно указать,
какая оболочка должна использоваться
для выполнения данного сценария. Это
можно сделать, разместив в первой строке
сценария последовательность символов
#!путь_к_программе-оболочке.
Например, если необходимо указать,
что для выполнения сценария следует
использовать оболочку bash,
первой строкой сценария должна быть
строка

#!/bin/bash

Сценарий может содержать комментарии.
Комментарий – это оператор, который
может размещаться в сценарии оболочки,
но оболочкой не исполняется. Комментарий
начинается с символа # и продолжается
до конца строки.

Ниже приведён пример короткого сценария:

#!/bin/sh

date

who

Примечание: несколько команд в
сценарии могут записываться в одну
строку. В качестве разделителя между
ними необходимо указывать точку с
запятой (;).
Например:

#!/bin/sh

date;
who;

Переменные

Переменная – это программный
объект, способный принимать значение.
Оболочка разрешает создавать и удалять
переменные, а также присваивать им
значения. В большинстве случаев
разработчик ответственен за управление
переменными в сценариях. Использование
переменных позволяет создавать гибкие,
легко адаптируемые сценарии. Имена
переменных определяются по тем же
правилам, что и в языке программирования
С.

Определяются переменные следующим
образом (отсутствие пробелов до и после
символа = существенно):

имя_переменной=значение

Все переменные по умолчанию имеют
строковый тип. Например, MY_NAME=Sergey
определяет переменную с именем MY_NAME
и присваивает ей значение Sergey.
В переменной можно сохранять любое
нужное значение. Особый случай – когда
это значение содержит пробелы. Для
правильного выполнения такого действия
указанное значение достаточно заключить
в кавычки.

Если переменной присвоена последовательность
чисел, то значение этой переменной будет
трактоваться как число. Например,
а=12345.
Теперь переменную а
можно использовать в арифметических
выражениях.

Для того чтобы получить значение
переменной, перед её именем необходимо
поставить знак $,
а имя переменной заключить в фигурные
скобки.

Например, в результате выполнения
команды

echo
a

на терминал выведется буква а,
а в результате выполнения команды

echo
${a}

будет напечатано число 12345.

Примечание: при подстановке значений
переменных фигурные скобки в большинстве
случаев можно опускать. Но обратите
внимание, что в результате выполнения
команды

echo
${a}1

к значению переменной а будет дописана
1, то есть получим значение 123451, а в
результате выполнения команды

echo
$a1

на терминал будет выведено значение
переменной a1,
если она определена в программе и ничего
не будет выведено, если переменная a1
не определена.

С помощью конструкции
${#имя_переменной}
можно получить количество символов в
определенной переменной (длину
переменной).

С помощью конструкции ${имя_переменной:m:n}
можно выделить подстроку из определенной
переменной (здесь где m
– номер позиции, начиная с которой будет
производиться выделение подстроки, а
n
– количество выделяемых символов).

Примечание: значение
n
можно опускать. Тогда будет
производиться выделение символов до
конца строки.

В том случае, когда некоторая переменная
становится ненужной, её можно удалить
с помощью команды unset
имя_переменной.

Ниже приведён пример, иллюстрирующий
работу с переменными в сценариях.

#!/bin/bash

MY_NAME=Sergey

MY_FULL_NAME=»Sergey
B. Sidorov»

echo
name = $MY_NAME and full name = $MY_FULL_NAME

echo
Length of my full name is ${#MY_FULL_NAME} symbols

echo
My surname is ${MY_FULL_NAME:10}

m=0

n=6

echo
My
name
is
${MY_FULL_NAME:m:n}
#подстановка
распространяется на

#все переменные в фигурных скобках

echo
${MY_FULL_NAME:10:5}

unset
MY_NAME

В результате выполнения сценария на
терминал будет выдано сообщение:

name
= Sergey and full name = Sergey B. Sidorov

Length
of my full name is 17 symbols

My
surname is Sidorov

My
surname is Sergey

Sidor

Все рассмотренные выше примеры переменных
– это примеры скалярных переменных,
то есть таких, которые могут хранить
только одно значение. Наряду с ними
можно использовать переменные-массивы.
Доступ к элементам массива осуществляется
операцией индексирования [].
Язык программирования оболочки не
требует предварительного объявления
переменной массивом с указанием его
размерности. При этом отдельные элементы
массива создаются по мере доступа к
ним. Ниже приведён пример работы с
массивом NAME.

#!/bin/sh

NAME[0]=Сергей

NAME[10]=Катя

NAME[2]=Лиза

echo
все имена: ${NAME[*]}

echo
${NAME[10]} и ${NAME[2]} сестры

Если вместо индекса элемента использовать
*,
результатом выражения будет список
значений всех элементов массива (в
данном случае таковых три).

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
Управление устройством и т. Д.

    Часто ошибочно полагают, что Линус Торвальдс разработал ОС Linux, но на самом деле он отвечает только за разработку ядра Linux.
    Полная система Linux = ядро + системные утилиты и библиотеки GNU + другие сценарии управления + сценарии установки.

    Что такое Shell

    Оболочка — это специальная пользовательская программа, которая предоставляет пользователю интерфейс для использования служб операционной системы. Shell принимает от пользователя удобочитаемые команды и преобразует их во что-то понятное ядру. Это интерпретатор языка команд, который выполняет команды, считанные с устройств ввода, таких как клавиатура, или из файлов. Оболочка запускается, когда пользователь входит в систему или запускает терминал.

    оболочка linux

    Shell можно разделить на две категории:

    • Командная строка
    • Графическая оболочка

    Командная строка

    Пользователь может получить доступ к оболочке с помощью интерфейса командной строки. Специальная программа под названием « Терминал» в linux / macOS или « Командная строка в ОС Windows» предназначена для ввода удобочитаемых команд, таких как «cat», «ls» и т. Д., А затем она выполняется. Затем результат отображается на терминале пользователю. Терминал в системе Ubuntu 16.4 выглядит так:

    командная строка linux

    На скриншоте выше выполняется команда «ls» с параметром «-l».

    Он перечислит все файлы в текущем рабочем каталоге в формате длинного списка.
    Работать с оболочкой командной строки немного сложно для новичков, потому что трудно запомнить так много команд. Это очень мощный инструмент, который позволяет пользователю сохранять команды в файле и выполнять их вместе. Таким образом, любую повторяющуюся задачу можно легко автоматизировать. Эти файлы обычно называются пакетными файлами в Windows и сценариями оболочки в системах Linux / macOS.

    Графические оболочки

    Графические оболочки предоставляют средства для управления программами на основе графического пользовательского интерфейса (GUI), позволяя выполнять такие операции, как открытие, закрытие, перемещение и изменение размеров окон, а также переключение фокуса между окнами. Окно ОС или ОС Ubuntu можно рассматривать как хороший пример, который предоставляет пользователю графический интерфейс для взаимодействия с программой. Пользователю не нужно вводить команду для каждого действия. Типичный графический интерфейс в системе Ubuntu —

    Оболочка графического интерфейса

    Для систем Linux доступно несколько оболочек, например:

    • BASH (Bourne Again SHell) — это наиболее широко используемая оболочка в системах Linux. Он используется в качестве оболочки входа по умолчанию в системах Linux и macOS. Его также можно установить в ОС Windows.
    • CSH (C SHell) — синтаксис и использование оболочки C очень похожи на язык программирования C.
    • KSH (Korn SHell) — Korn Shell также была базой для стандартных спецификаций POSIX Shell и т. Д.

    Каждая оболочка выполняет одну и ту же работу, но понимает разные команды и предоставляет разные встроенные функции.

    Сценарии оболочки

    Обычно оболочки интерактивны, что означает, что они принимают команды в качестве входных данных от пользователей и выполняют их. Однако какое-то время мы хотим регулярно выполнять кучу команд, поэтому мы каждый раз вводим все команды в терминале.
    Поскольку оболочка также может принимать команды в качестве входных данных из файла, мы можем записывать эти команды в файл и выполнять их в оболочке, чтобы избежать этой повторяющейся работы. Эти файлы называются сценариями оболочки или программами оболочки . Сценарии оболочки похожи на командный файл в MS-DOS. Каждый сценарий оболочки сохраняется с расширением файла .sh, например. myscript.sh

    Сценарий оболочки имеет синтаксис, как и любой другой язык программирования. Если у вас есть опыт работы с любым языком программирования, таким как Python, C / C ++ и т. Д., Было бы очень легко начать с ним.
    Сценарий оболочки состоит из следующих элементов —

    • Ключевые слова оболочки — if, else, break и т. Д.
    • Команды оболочки — cd, ls, echo, pwd, touch и т. Д.
    • Функции
    • Поток управления — if..then..else, case, shell и т. Д.

    Зачем нужны сценарии оболочки

    Есть много причин писать сценарии оболочки —

    • Чтобы избежать повторяющейся работы и автоматизации
    • Системные администраторы используют сценарии оболочки для рутинного резервного копирования
    • Системный мониторинг
    • Добавление новой функциональности в оболочку и т. Д.

    Преимущества сценариев оболочки

    • Команда и синтаксис точно такие же, как и те, которые вводятся непосредственно в командной строке, поэтому программисту не нужно переключаться на совершенно другой синтаксис.
    • Написание сценариев оболочки намного быстрее
    • Быстрый старт
    • Интерактивная отладка и т. Д.

    Недостатки сценариев оболочки

    • Склонность к дорогостоящим ошибкам, одна ошибка может изменить команду, что может быть опасным.
    • Медленная скорость исполнения
    • Недостатки дизайна в синтаксисе или реализации языка
    • Не подходит для больших и сложных задач
    • Обеспечьте минимальную структуру данных в отличие от других языков сценариев. так далее

    Простая демонстрация сценариев оболочки с использованием Bash Shell

    Если вы работаете на терминале, вы путешествуете по каталогам глубоко. Затем для перехода на несколько каталогов по пути мы должны выполнить команду, подобную этой, как показано ниже, чтобы перейти в каталог «python» —

    Это довольно неприятно, так почему бы нам не иметь утилиту, в которой нам просто нужно ввести имя каталога, и мы можем напрямую переходить к нему, не выполняя команду «cd ../» снова и снова. Сохраните сценарий как «jump.sh».

    function jump()

    {

    OLDIFS=$IFS

    IFS=/

    path_arr=($PWD)

    IFS=$OLDIFS

    local pos=-1

    for dir in "${path_arr[@]}"

    do

    pos=$[$pos+1]

    if [ "$1" = "$dir" ]; then

    dir_in_path=${

    cwd=$PWD

    limit=$[$dir_in_path-$pos-1]

    for ((i=0; i<limit; i++))

    do

    cwd=$cwd/..

    done

    cd $cwd

    break

    fi

    done

    }

    На данный момент мы не можем выполнить наш сценарий оболочки, потому что у него нет разрешений. Мы должны сделать его исполняемым, набрав следующую команду —

    $ chmod -x путь / к / нашему / файлу / jump.sh
    

    Теперь, чтобы сделать это доступным в каждом сеансе терминала, мы должны поместить это в файл «.bashrc».
    «.Bashrc» — это сценарий оболочки, который оболочка Bash запускает всякий раз, когда запускается в интерактивном режиме. Цель файла .bashrc — предоставить место, где вы можете настроить переменные, функции и псевдонимы, определить нашу подсказку и определить другие настройки, которые мы хотим использовать всякий раз, когда мы открываем новое окно терминала.
    Теперь откройте терминал и введите следующую команду —

    $ echo «источник ~ / путь / к / нашему / файлу / jump.sh» >> ~ / .bashrc
    

    Теперь откройте терминал и попробуйте новую функцию «прыжка», набрав следующую команду:

    $ jump dir_name
    

    как показано на скриншоте ниже —

    Ресурсы для изучения сценариев Bash

    • https://bash.cyberciti.biz/guide/The_bash_shell
    • http://tldp.org/LDP/abs/html/

    использованная литература

    • https://en.wikipedia.org/wiki/Shell_script
    • https://en.wikipedia.org/wiki/Shell_(computing)

    Эта статья предоставлена Атулом Кумаром . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью с помощью provide.geeksforgeeks.org или отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам. Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное или хотите поделиться дополнительной информацией по теме, обсуждаемой выше.

Понравилась статья? Поделить с друзьями:
  • Сценарии концертов про родину
  • Сценарии на визитку класса
  • Сценарии знаменитых фильмов читать
  • Сценарии концертов на белорусском языке
  • Сценарии нравственного эстетического воспитания