====== Bash ====== ------------------------------- A shell and scripting language ------------------------------- .. class:: right Morgan Goose Febuary 2011 .. class:: handout This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/us/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. Shell like any other ==================== Bash is an acronym for **Bourne-Again SHell**. The Bourne shell is the traditional Unix shell originally written by Stephen Bourne. All of the Bourne shell builtin commands are available in Bash, The rules for evaluation and quoting are taken from the posix specification for the **standard** Unix shell. Variables ========= To set a variable, and then use it you'd do this .. code-block:: bash $ a="some val" $ echo $a some val $ A bit more on variables ======================= Appending is possiable .. code-block:: bash $ x="hello" $ x+=" world" $ echo $x hello world Quotes and stuff ================ Single quotes ' don't expand varables inside them Double quotes " do Words of the form $'string' expand to ANSI C backslash-escaped characters Expansion ========= Expansion is performed on the command line after it has been split into tokens. There are seven kinds of expansion performed. Types avaliable are: * brace expansion * tilde expansion * parameter and variable expansion * command substitution * arithmetic expansion Not covering * process substitution * word splitting * filename expansion Brace Expansion =============== .. code-block:: bash $ echo a{d,c,b}e ade ace abe Can be nested .. code-block:: bash $ echo /usr/{ucb/{ex,edit},lib/{ex?.?**,how_ex}} /usr/ucb/ex /usr/ucb/edit /usr/lib/ex?.?** /usr/lib/how_ex Tilde Expansion =============== Normal:: ~ The value of $HOME ~/foo $HOME/foo ~fred/foo The subdirectory foo of the home directory of the user fred ~+/foo $PWD/foo ~-/foo ${OLDPWD-'~-'}/foo If using dir stacks:: ~N The string that would be displayed by **dirs +N** ~+N The string that would be displayed by **dirs +N** ~-N The string that would be displayed by **dirs -N** Parameter and Variable ====================== The **$** character introduces parameter expansion, command substitution, or arithmetic expansion. **${parameter:−word}** If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. **${parameter:=word}** If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. **${parameter:+word}** If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted. **${parameter:offset}** Expands to up to length characters of parameter starting at the character specified by offset. **${parameter:offset:length}** In use ======= .. code-block:: bash $ echo "${echo:-else}" else $ x="" $ ${x:="hellow world"} $ echo $x hello world $ echo "${x:5}" world $ echo "${x:0:5}" hello Command Substitution ==================== Command substitution allows the output of a command to replace the command itself. Command substitution occurs when a command is enclosed as follows: .. code-block:: bash $(command) or `command` Arithmetic Expansion ==================== Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is: $(( expression )) .. code-block:: bash $ echo $((1+3)) 4 Chaining and Pipes ================== A pipeline is a sequence of simple commands separated by one of the control operators **|** or **|&** If **|&** is used, the standard error of command1 is connected to command2's standard input through the pipe; it is shorthand for **2>&1 |**. This implicit redirection of the standard error is performed after any redirections specified by the command. A list is a sequence of one or more pipelines separated by one of the operators **;**, **&**, **&&**, or **||**, and optionally terminated by one of **;**, **&**, or a newline. Of these list operators, **&&** and **||** have equal precedence, followed by **;** and **&**, which have equal precedence. A sequence of one or more newlines may appear in a list to delimit commands, equivalent to a semicolon. If a command is terminated by the control operator **&**, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. Loops! ====== Bash supports the following looping constructs. Note that wherever a **;** appears in the description of a command's syntax, it may be replaced with one or more newlines. **until** The syntax of the until command is:: until test-commands; do consequent-commands; done **while** The syntax of the while command is:: while test-commands; do consequent-commands; done **for** The syntax of the for command is:: for name [ [in [words ...] ] ; ] do commands; done Conditionals ============ If == The syntax of the if command is:: if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fi Case ==== The syntax of the case command is:: case word in [ [(] pattern [| pattern]...) command-list ;;]... esac Each clause must be terminated with ‘;;’, ‘;&’, or ‘;;&’. Here is an example:: case $ANIMAL in horse | dog | cat) echo -n "four";; man | kangaroo ) echo -n "two";; **) echo -n "an unknown number of";; esac echo " legs." If the ‘;;’ operator is used, no subsequent matches are attempted after the first pattern match. Using ‘;&’ in place of ‘;;’ causes execution to continue with the command-list associated with the next clause, if any. Using ‘;;&’ in place of ‘;;’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match. Select ====== The select construct allows the easy generation of menus. It has almost the same syntax as the for command:: select name [in words ...]; do commands; done The list of words following in is expanded, generating a list of items. The commands are executed after each selection until a break command is executed, at which point the select command completes. Here is an example that allows the user to pick a filename from the current directory, and displays the name and index of the file selected .. code-block:: bash select fname in **; do echo you picked $fname \($REPLY\) break; done Other expressions ================= **(( expression ))** The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to:: let "expression" **[[ expression ]]** Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below in Bash Conditional Expressions. Group Commands ============== When commands are grouped, redirections may be applied to the entire command list. **( list )** Placing a list of commands between parentheses causes a subshell environment to be created (see Command Execution Environment), and each of the commands in list to be executed in that subshell. Since the list is executed in a subshell, variable assignments do not remain in effect after the subshell completes. **{ list; }** Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required. Redirections ============ Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection may also be used to open and close files for the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right. Note that the order of redirections is significant. For example, the command:: ls > dirlist 2>&1 directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist, while the command:: ls 2>&1 > dirlist directs only the standard output to file dirlist, because the standard error was made a copy of the standard output before the standard output was redirected to dirlist. Job Control =========== **bg** resume a suspended job, and run in background (as if it had been run with &) **fg** resume current backgrounded process in the forground **jobs** list all current backgrounded jobs **disown** has each jobspec is removed from the table of active jobs, so SIGHUP won't kill backgrounded jobs. History Expansion ================= How to manipulate past commands:: **!n** Refer to command line n. **!-n** Refer to the command n lines back. **!!** Refer to the previous command. This is a synonym for ‘!-1’. **!string** Refer to the most recent command starting with string. **string1^string2^** Quick Substitution. Repeat the last command, replacing string1 with string2 **!!:gs/string1/string2/** Cause changes to be applied over the entire event line. More things =========== That could be talked about later: * builtins, actual scripting * readline manipulation * tests * coprocess * indepth stream manipulation * traps, signals, and exit codes * bash specific variables