
CODING BASH BASH: BEYOND THE TUTORIAL COMMAND PROMPT Speed up repetitive tasks, get more power out of the command line JOHN LANE or just make life easier – welcome to the world of Bash scripting. ost Linux users will know Bash as the program loader to start it. This creates, or forks, a WHY DO THIS? command line prompt. But it is also a child process of your shell. • Chain commands powerful programming language – a lot of But the script isn’t a binary executable, so the together to create M flexible scripts. the code that glues the various parts of your system program loader needs to be told how to execute it. • Get more from the together is written in Bash. You may have looked at You do this by including a special directive as the first command line. some of it and seen seas of parentheses, braces and line of your script, which is why most bash scripts • Learn a new way of brackets. This less-than obvious syntax helps make begin with a line this: working. other languages, such as Python, more attractive to #!/bin/bash beginners. But Bash is ubiquitous in the Linux world, The first two characters, #!, known as a shebang, and it’s worth taking the time to learn how to go are detected by the program loader as a magic beyond the prompt. number that tells it that the file is a script and that it A good introduction to Bash programming is to put should interpret the remainder of the line as the frequently issued command sequences into a file so executable to load – plus, optionally, any arguments that you can replay them at the command prompt to pass to it along with the script itself. The program instead of typing each one. Such a file is called a loader starts \bin\bash in a new process, and this script, and we often hear “scripting” instead of runs the script. It needs the absolute path to the “programming”. Bash is nonetheless a language with executable because the kernel has no concept of a its own syntax, capabilities and limitations. search path (that is itself a feature of the shell). Scripts that perform specific tasks are usually The basics executed so they run in a predictable environment. Bash programs, like Python and Ruby, are not Every process has an environment that it inherits from compiled into binary executables, but need to be its parent, and contains so-called environment parsed by an interpreter. For Bash, this is an variables that offer its parent a way to pass executable called bash that interprets commands information into it. A process can alter its own read interactively from its command prompt or from a environment and prepare that of its children, but it script. If you’re at a Bash prompt, it’ll be provided by a cannot affect its parent. running bash process, and you can feed a script Scripts specifically written to alter the current straight to it: environment (like rc files) are sourced and usually $ source myscript don’t have their execute bit set. But you may not be at such a prompt (you might use another shell, such as csh or ksh, or you may be at One line at a time the Run dialog of your desktop). If you set the execute Bash reads input one line at a time, whether from a bit on your script: command prompt or a script. Comments are $ chmod +x myscript discarded; they start with a hash # character and then you can execute it: continue to the end of the line (bash sees the shebang $ myscript as a comment). It applies quoting rules and parameter which causes your shell to ask the operating system’s expansion to what remains and ends up with words – commands, operators and keywords that make up the language. Commands are executed and return an POSIX exit status, which is stored in a special variable for use by subsequent commands. An IEEE standard for a portable operating can run in a POSIX-compliant mode. The system interface, POSIX is frequently bash command does this when launched in Words are separated by metacharacters: a space or mentioned in texts about shell scripting. It this way or if given the --posix command- one of |, &, ;, (, ), < or >. Operators are character means being compatible with something line option. sequences containing one or more metacharacters. called the Shell Command Language, which In POSIX mode, Bash only supports the Metacharacters can have their special meaning is defined by an IEEE standard and features defined by the POSIX standard. removed by quoting. The first form of quoting implemented as the shell on all Unix-like Anything else is commonly called a bashism. systems by the /bin/sh command.These days See http://bit.ly/bashposix for what’s removes special meaning from all characters /bin/sh is usually a symlink to a shell that different in Bash’s POSIX mode. enclosed by single quotes. It is not possible to enclose a single quote within single quotes. Double quotes are 100 www.linuxvoice.com BASH CODING case names for your own variables and use upper Chain of command case names for constants and environment variables. Parameter expansion happens when a parameter’s Bash expects one command per line, but this can be a chain: a sequence of commands connected together with name is preceded by the dollar sign, and it replaces one of four special operators. Commands chained with && the parameter with its value: only execute if the exit status of the preceding one was 0, echo $1 indicating success. Conversely, commands chained with which outputs the script’s first argument. These || execute only if the preceding one failed. Commands so-called positional parameters are numbered chained with a semicolon (;) execute irrespective of how the prior command exited. Lastly, the single-ampersand upwards from 1 and 0 contains the filesystem path to & operator chains commands, placing the preceding the script. Parameter names can be enclosed by { and command into the background: } if their names would otherwise be unclear. Consider command1 && command2 # perform command2 only if this: command1 succeeded $ var=1234 command1 || command2 # perform command2 only if command1 failed $ echo $var5678 command1 ; command2 # perform command1 and then $ echo ${var}5678 command2 12345678 command1 & command2 # perform command2 after starting The first echo receives the value of a non-existant command1 in the background variable var5678 whereas the second gets the value of Chains can be combined, giving a succinct if-then-else var, followed by 5678. The other thing to understand construct: PRO TIP command1 && command2 || command3 about parameters is that bash expands them before The exit status of a chain is the exit status of the last any command receives them as arguments. If this You can use a “.” instead command to execute. of “source” to run a expansion includes argument separators, then the script in the current expanded value will become multiple arguments. You’ll environment. encounter this when values contain spaces, and the similar, except some metacharacters still work, most solution to this problem is quoting: notably the Dollar sign, which performs parameter $ file=’big data’ expansion, and the escape \, which is the third form of $ touch “$file” quoting and removes special meaning from the $ ls $file following character only. ls: cannot access big: No such file or directory Parameters pass information into the script. ls: cannot access data: No such file or directory Positional parameters contain the script’s argument Here, touch creates a file called big data because list, and special variables provide ways to access them the file variable is quoted, but ls fails to list it because en-masse and also provide other information like the it is unquoted and therefore receives two arguments script’s filesystem path, its process ID and the last instead of one. command’s exit status. For these two reasons, it is common to quote and Variables are parameters that you can define by delimit parameters when expanding them; many assigning a value to a name. Names can be any string scripts refer to variables like this: of alphanumeric characters, plus the underscore (_) “${myvar}” but cannot begin with a numeric character, and all Braces are also required to expand array variables. values are character strings, even numbers. Variables These are defined using parentheses and expanded don’t need to be declared before use, but doing so with braces: enables additional attributes to be set such as making $ myarr=(foo bar baz) them read-only (effectively a constant) or defining $ echo “${myarr[@]}” # values them as an integer or array (they’re still string values foo bar baz though!). Assignment is performed with the = operator $ echo “${!myarr[@]}” # indices and must be written without spaces between the name and value. Here are some examples that you Special Variables might see: 0 The name of the shell (if interactive) or script. var1=hello 1 .. n The positional parameters numbered from 1 to the var2=1234 number of arguments n. Braces must be used when declare -i int=100 # integer expanding arguments greater than 9 (eg ${10}). declare -r CON=123 # constant * All the positional parameters. Expanding within declare -a arr=(foo bar baz) # array quotes gives a single word containing all parameters separated by spaces (eg “$*” is equivalent to “$1 $2 Variables default to being shell variables; they aren’t ... $n”). part of the environment passed to child processes. @ All the positional parameters. Expanding within For that to happen, the variable must be exported as quotes gives all parameters, each as a separate word an environment variable: (eg “$@” is equivalent to “$1 $2 ..
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages4 Page
-
File Size-