What does bash mean in linux




















There are hundreds of commands available for Linux and Unix, and it might surprise you just how diverse they are. For instance, you can resize and crop photos without ever opening the photo in a viewer or editor:.

You can play music with commands like ogg or mpg , convert audio with sox , adjust and edit video with ffmpeg , edit text with emacs or vim , check email with pine or mutt , browse the internet with elinks , browse files with ranger or midnightcommander , and do much, much more.

It's all done in Bash, using the commands you find on your system or in your software repository. One reason Bash and Linux in general is considered so powerful is because it's scriptable. Anything you can type into Bash manually, you can also list in a plain-text file and have Bash run it for you.

Instead of spending an afternoon manually running a hundred commands, you can script the commands and have your computer execute them while you tend to more important matters. Because nearly everything on Linux runs on top of the Bash shell, nearly everything on Linux can be scripted through Bash. While there are exceptions to this graphical applications may have their own scripting language, for instance, or no scripting at all , scripting your OS opens up tens of thousands of possible functions you can make happen on your computer without doing them yourself.

The amount of work this saves Linux users each day is impossible to estimate. It's not the usual automation that makes the difference, though; it's the bespoke workflows that people invent for themselves, the things nobody else thinks need automation. When experienced users say that they want to learn Bash, if they don't mean they want to learn Linux commands, then they probably mean that they want to improve the way they script their commands.

For instance, this is an extremely rudimentary Bash script that converts a temporary file imagine it's a file created by a separate process to a specific directory:. That's valid Bash. You can verify it by copying and pasting the command the last line beginning with cp into a terminal. Executed commands inherit the environment. The export and declare -x commands allow parameters and functions to be added to and deleted from the environment.

If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell's initial environment, whose values may be modified in the shell, less any pairs removed by the unset command, plus any additions via the export and declare -x commands. The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in the section " Parameters.

If the -k option is set see the set builtin command below , then all parameter assignments are placed in the environment for a command, not only those that precede the command name. The exit status of an executed command is the value returned by the waitpid system call or equivalent function.

Exit statuses fall between 0 and , though, as explained below, the shell may use values above specially. Exit statuses from shell builtins and compound commands are also limited to this range. Under certain circumstances, the shell uses special values to indicate specific failure modes.

For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure. If a command is not found, the child process created to execute it returns a status of If a command is found but is not executable, the return status is If a command fails because of an error during expansion or redirection, the exit status is greater than zero.

Shell builtin commands return a status of 0 true if successful, and non-zero false if an error occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage. Bash itself returns the exit status of the last command executed, unless a syntax error occurs, where it exits with a non-zero value.

See also the exit builtin command below. Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. To prevent the shell from sending the signal to a particular job, it should be removed from the jobs table with the disown builtin see the section " Shell Builtin Commands " below or marked to not receive SIGHUP using disown -h.

If the huponexit shell option is set with shopt , bash sends a SIGHUP to all jobs when an interactive login shell exits. If bash is waiting for a command to complete and receives a signal for which a trap is set, the trap is not executed until the command completes.

When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap is set causes the wait builtin to return immediately with an exit status greater than , immediately after which the trap is executed.

Job control refers to the ability to selectively stop suspend the execution of processes and continue resume their execution at a later point. A user often employs this facility via an interactive interface supplied jointly by the operating system kernel 's terminal driver and bash.

The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs command. When bash starts a job asynchronously in the background , it prints a line that looks like:. Indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is All the processes in a single pipeline are members of the same job.

Bash uses the job abstraction as the basis for job control. To facilitate the implementation of the user interface to job control, the operating system maintains the notion of a current terminal process group ID. These processes are said to be in the foreground. Background processes are those whose process group ID differs from the terminal's; such processes are immune to keyboard-generated signals. Only foreground processes are allowed to read from or, if the user so specifies with stty tostop, write to the terminal.

If the operating system on which bash is running supports job control, bash contains facilities to use it. The user may then manipulate the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it.

There are many ways to refer to a job in the shell. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. If a prefix matches more than one job, bash reports an error. If the substring matches more than one job, bash reports an error.

In output for jobs e. The shell learns immediately whenever a job changes state. Normally, bash waits until it is about to print a prompt before reporting changes in a job's status so as to not interrupt any other output. If the -b option to the set builtin command is enabled, bash reports such changes immediately. If an attempt to exit bash is made while jobs are stopped or, if the checkjobs shell option is enabled using the shopt builtin, running , the shell prints a warning message, and, if the checkjobs option is enabled, lists the jobs and their statuses.

The jobs command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, the shell does not print another warning, and any stopped jobs are terminated. When executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be customized by inserting backslash-escaped special characters that are decoded as follows:.

The command number and the history number are usually different: the history number of a command is its position in the history list, which may include commands restored from the history file see the section " History ", below , while the command number is the position in the sequence of commands executed during the current shell session. After the string is decoded, it is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal, subject to the value of the promptvars shell option see the description of the shopt command under " Shell Builtin Commands " section below.

This is the library that handles reading input when using an interactive shell, unless the --noediting option is given at shell invocation. Line editing is also used when using the -e option to the read builtin. By default, the line editing commands are similar to those of Emacs.

A vi -style line editing interface is also available. Line editing can be enabled at any time using the -o emacs or -o vi options to the set builtin see the section " Shell Builtin Commands " below. In this section, the Emacs -style notation is used to denote keystrokes. Control keys are denoted by C -key, e. Similarly, meta keys are denoted by M -key, so M-x means Meta-X. On keyboards without a meta key, M-x means ESC x , i. This makes ESC the meta prefix.

Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of the argument that is significant. Passing a negative argument to a command that acts in the forward direction e. Commands whose behavior with arguments deviates from this are noted below.

When a command is described as killing text, the text deleted is saved for possible future retrieval yanking. The killed text is saved in a kill ring. Consecutive kills cause the text to be accumulated into one unit, which can be yanked all at once.

Commands which do not kill text separate the chunks of text on the kill ring. Readline is customized by putting commands in an initialization file the inputrc file. When a program which uses the readline library starts up, the initialization file is read, and the key bindings and variables are set.

There are only a few basic constructs allowed in the readline initialization file. Blank lines are ignored. Lines beginning with a are comments. Other lines denote key bindings and variable settings. The default key-bindings may be changed with an inputrc file. Other programs that use this library may add their own commands and bindings. In the inputrc would make M-C-u execute the readline command universal-argument.

In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed a macro. The syntax for controlling key bindings in the inputrc file is simple.

All that is required is the name of the command or the text of a macro and a key sequence that it should be bound. The name may be specified in one of two ways: as a symbolic key name, possibly with Meta- or Control- prefixes, or as a key sequence. When using the form keyname:function-name or macro, keyname is the name of a key spelled out in English.

For example:. In the second form, "keyseq":function-name or macro , keyseq differs from keyname above in that strings denoting an entire key sequence may be specified by placing the sequence within double quotes.

Some GNU Emacs style key escapes can be used, as in the following example, but the symbolic character names are not recognized. In this example, C-u is again bound to the function universal-argument.

In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available:. When entering the text of a macro , single or double quotes must indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Backslash quotes any other character in the macro text, including " and '. Bash allows the current readline key bindings to be displayed or modified with the bind builtin command. The editing mode may be switched during interactive use using the -o option to the set builtin command see the section " Shell Builtin Commands " below.

Readline has variables that further customize its behavior. A variable may be set in the inputrc file with a statement of the form. Except where noted, readline variables can take the values On or Off without regard to case. Unrecognized variable names are ignored. When a variable value is read, empty or null values, " on " case-insensitive , and " 1 " are equivalent to On. All other values are equivalent to Off. The variables and their default values are:.

Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor that allows key bindings and variable settings to be performed as the result of tests.

There are four parser directives used. Readline provides commands for searching through the command history see section " History " below for lines containing a specified string.

There are two search modes: incremental and non-incremental. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable are used to terminate an incremental search.

If that variable is not assigned a value, the Escape and Control-J characters terminate an incremental search. Control-G aborts an incremental search and restore the original line. When the search is terminated, the history entry containing the search string becomes the current line. To find other matching entries in the history list, type Control-S or Control-R as appropriate.

This searches backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a readline command terminates the search and execute that command. For instance, a newline terminates the search and accept the line, thereby executing the command from the history list. Readline remembers the last incremental search string. If two Control-R s are typed without any intervening characters defining a new search string, any remembered search string is used.

Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line. The following is a list of the names of the commands and the default key sequences that they are bound.

Command names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region.

When word completion is attempted for an argument to a command for which a completion specification a compspec is defined using the complete builtin see the section " Shell Builtin Commands " below , the programmable completion facilities are invoked. First, the command name is identified. If the command word is the empty string completion attempted at the beginning of an empty line , any compspec defined with the -E option to complete is used. If a compspec is defined for that command, the compspec is used to generate the list of possible completions for the word.

If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash. If those searches do not result in a compspec , any compspec defined with the -D option to complete is used as the default. Once a compspec is found, it is used to generate the list of matching words. If a compspec is not found, the default bash completion as described above under Completing is performed.

First, the actions specified by the compspec are used. Only matches which are prefixed by the word being completed are returned. Any completions specified by a pathname expansion pattern to the -G option are generated next. The words generated by the pattern need not match the word being completed.

Next, the string specified as the argument to the -W option is considered. The string is first split using the characters in the IFS special variable as delimiters. Shell quoting is honored. Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion, as described above under the section " Expansion.

After these matches are generated, any shell function or command specified with the -F and -C options is invoked. When the function or command is invoked, the first argument is the name of the command whose arguments are being completed, the second argument is the word being completed, and the third argument is the word preceding the word being completed on the current command line.

No filtering of the generated completions against the word being completed is performed; the function or command has complete freedom in generating the matches. Any function specified with -F is invoked first. The function may use any of the shell facilities, including the compgen builtin described below, to generate the matches.

Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output.

Backslash may be used to escape a newline, if necessary. After all the possible completions are generated, any filter specified with the -X option is applied to the list.

Any completion that matches the pattern is removed from the list. A leading! Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the result is returned to the readline completion code as the list of possible completions. If the previously-applied actions do not generate any matches, and the -o dirnames option was supplied to complete when the compspec was defined, directory name completion is attempted.

If the -o plusdirs option was supplied to complete when the compspec was defined, directory name completion is attempted and any matches are added to the results of the other actions. By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default bash completions are not attempted, and the readline default of file name completion is disabled. If the -o bashdefault option was supplied to complete when the compspec was defined, the bash default completions are attempted if the compspec generates no matches.

If the -o default option was supplied to complete when the compspec was defined, readline's default completion is performed if the compspec and, if attempted, the default bash completions generate no matches. When a compspec indicates that directory name completion is desired, the programmable completion functions force readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories readline variable, regardless of the setting of the mark-symlinked-directories readline variable.

There is some support for dynamically modifying completions. This is most useful when used in combination with a default completion specified with complete -D. It's possible for shell functions executed as completion handlers to indicate that completion should be retried by returning an exit status of If a shell function returns , and changes the compspec associated with the command on which completion is being attempted supplied as the first argument when the function is executed , programmable completion restarts from the beginning, with an attempt to find a new compspec for that command.

This allows a set of completions to be built dynamically as completion is attempted, rather than being loaded all at once.

For instance, assuming that there is a library of compspecs , each kept in a file corresponding to the name of the command, the following default completion function would load completions dynamically:. When the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands previously typed. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the preceding history line.

If the histappend shell option is enabled see the description of shopt under the section " Shell Builtin Commands " below , the lines are appended to the history file, otherwise the history file is overwritten.

This uses the history comment character to distinguish timestamps from other history lines. The builtin command fc see the " Shell Builtin Commands " section below may be used to list or edit and re-execute a portion of the history list.

The history builtin may be used to display or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that access the history list. The shell allows control over which commands are saved on the history list.

The cmdhist shell option, if enabled, causes the shell to attempt to save each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correctness. The lithist shell option causes the shell to save the command with embedded newlines instead of semicolons.

See the description of the shopt builtin below under the section " Shell Builtin Commands " for information on set ting and unset ting shell options. The shell supports a history expansion feature that is similar to the history expansion in csh.

This section describes what syntax features are available. Non-interactive shells do not perform history expansion by default. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly.

History expansion is performed immediately after a complete line is read, before the shell breaks it into words. It takes place in two parts. The first is to determine which line from the history list to use during substitution.

The second is to select portions of that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line that are acted upon are words.

Various modifiers are available to manipulate the selected words. The line is broken into words in the same fashion as when reading input, so that several metacharacter-separated words surrounded by quotes are considered one word. History expansions are introduced by the appearance of the history expansion character, which is! If the extglob shell option is enabled, also inhibits expansion. Several shell options settable with the shopt builtin may be used to tailor the behavior of history expansion.

If the histverify shell option is enabled see the description of the shopt builtin below , and readline is used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the readline editing buffer for further modification. If readline is used, and the histreedit shell option is enabled, a failed history substitution is reloaded into the readline editing buffer for correction.

The -p option to the history builtin command may be used to see what a history expansion does before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall.

The shell allows control of the various characters used by the history expansion mechanism see the description of histchars above under the section " Shell Variables ". The shell uses the history comment character to mark history timestamps when writing the history file.

An event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are relative to the current position in the history list. Word designators are used to select desired words from the event.

A : separates the event specification from the word designator. Words are numbered from the beginning of the line, with the first word being denoted by 0 zero. Words are inserted into the current line separated by single spaces. If a word designator is supplied without an event specification, the previous command is used as the event. After the optional word designator, there may appear a sequence of one or more of the following modifiers , each preceded by a ' : '. Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options.

The : , true , false , and test builtins do not accept options and do not treat -- specially. The exit , logout , break , continue , let , and shift builtins accept and process arguments beginning with - without requiring Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with - as invalid options and require -- to prevent this interpretation.

If bash is started with the name rbash , or the -r option is supplied at invocation, the shell becomes restricted.

A restricted shell is used to set up an environment more controlled than the standard shell. It behaves identically to bash with the exception that the following are disallowed or not performed:. When a command that is a shell script is executed see the section " Command Execution " above , rbash turns off any restrictions in the shell spawned to execute the script.

Launches the bash command interpreter. The remainder of the examples assume you are at a bash prompt. Home Help Linux. Related pages How to customize the command prompt in bash. Was this page useful? If the -c option is present, then commands are read from string.

If the -i option is present, the shell is interactive. For more information about interactive shells, see invocation , below. Make bash act as if it had been invoked as a login shell.

See the " Invocation " section below for more details. If the -r option is present, the shell becomes restricted see the " Restricted Shell " section below for more details. If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input.

This option allows the positional parameters to be set when invoking an interactive shell. This implies the -n option; no commands are executed. A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as file names and arguments. An argument of - is equivalent to Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode see the description of the extdebug option to the shopt builtin below.

Equivalent to -D , but the output is in the GNU gettext po portable object file format. By default, bash reads these files when it is invoked as a login shell see the " Invocation " section below for details. This option is on by default if the shell is invoked as sh. Change the behavior of bash where the default operation differs from the POSIX standard to match the standard. The shell becomes restricted see the " Restricted Shell " section below for details.

A sequence of characters considered as a single unit by the shell. Also known as a token. A word consisting only of alphanumeric characters and underscores, and beginning with alphabetic character or an underscore. Also referred to as an identifier. However, there are also subtle differences try echo --version. Why this duplication of commands? There are several reasons. The built-in version typically exists for performance reasons: Bash built-ins execute within the shell process that's already running.

In contrast, executing an external utility involves loading and executing the external binary by the kernel, which is a much slower process. At this point, it's useful to note that some shell commands, by their nature, cannot be external utilities in other words, they must be shell built-ins. Consider the cd command that changes the current working directory.

An external utility wouldn't be able to change the shell's current working directory, so cd must be a Bash built-in. Because invoking a command as an external utility would make the shell its parent process, and a child process cannot change the current working directory of the parent process. A practical problem users often face is this: how do you know whether the command you just called is the shell built-in or an external utility with the same name? The Bash command type which is itself a shell built-in indicates what command would be used if executed.

For example:. The basic rule is as follows: if the built-in command with a given name exists, it will be executed. If the built-in command doesn't exist, Bash will search for an external program, and if found, will execute it. If you want to be sure to use the executable, which happens to have the same name as a shell built-in, calling the executable with the full path will do. When a command is entered in Bash, Bash expects that the first word it encounters is a command.

This has assigned the value 7 to the variable named VAR. To retrieve the value of a variable, you need to prefix the variable name with the dollar sign.

Thus, to view the value of a variable, you can combine the dollar-sign prefix with echo :. The following will fail:. This clearly isn't what was intended here. Although Bash allows you to create arbitrary variables on the fly simply by assigning the values to them, it also has a number of built-in variables. This contains the process ID of the Bash shell itself:.

Another built-in variable and one that I cover extensively here is? At any point in a Bash session, this variable contains the return value of the last executed command.

The return value is always an integer. And specifically, this is the return value of the C program function main. Note: in any C program the function main must return an integer. By the UNIX convention, the return value of 0 denotes success, and any other value denotes failure. In the last example, note that the first? Because the second?

Remember, the? You can use the commands true and false to set the value of? Now let's consider how Bash provides an impression of a seamlessly integrated command environment, even when the tasks it executes are inherently quite different. First, note that running a Bash built-in command produces the same effect on the?

This example shows that calling the built-in command echo changed? The point is that it behaves the same as calling the external program echo :. Yet, these two scenarios are quite different. The effect on the? From this, you can see that Bash treats a variable assignment as a command. If the variable assignment is not successful,? So this will fail:.

Attempting to execute a non-existent command would also set? In this case, Bash filled the special variable? This number is hard-wired in Bash, and it specifically means "command not found". To summarize, the above examples show three completely different scenarios: invoking an internal Bash command, running an external program and variable assignment. Yet, Bash views all three as command execution and provides a common behavior with respect to the? Armed with these insights, now let's examine three basic programming constructs in Bash: the if statement, the while loop and the until loop.

The fundamental element of almost every programming language is the conditional if statement. In the C language, it looks like this:. This is sometimes called "truth value testing".

Here's an example of this in Python:. This looks very much like the if conditional statement in any programming language. However, it's not. In the above example, true is a command. In fact, true is a shell built-in:. Let that sink in: true is a command. In fact, that's the same true command that was run above from the command line to set the value of the? What then is the if statement evaluating? It's evaluating the return value of the true command.

Notice how the blank line was printed before the string Yay true! We also have articles here on Make Use Of that will train you to become a better Bash scripter.

We can show you for example how to write for loops in Bash , or maybe turn your scripts into clickable apps. We've learned about what Bash is, its history, and how you can learn to put it to work for you. Learning Bash is just one part, however, of getting the most out of your Linux operating system.

There's a lot more you can learn to become a Linux power user. Want to get better at using Linux? These Ubuntu tips and tricks will help you become a power user in no time. Jordan is a staff writer at MUO who's passionate about making Linux accessible and stress-free for everyone.

He also writes guides on privacy and productivity.



0コメント

  • 1000 / 1000