Bash Scripting: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
(→Tests) |
||
Line 19: | Line 19: | ||
* -n checks if a string is not empty, -z if it is empty. | * -n checks if a string is not empty, -z if it is empty. | ||
* [ is not a keyword but a command (a program!). It is recommended to use [[ in tests which is a keyword. | * [ is not a keyword but a command (a program!). It is recommended to use [[ in tests which is a keyword. | ||
* Note that [[ myVariable ]] will output true even if myVariable is equal to 0. The test must be explicit. | * Note that <nowiki>[[ myVariable ]]</nowiki> will output true even if myVariable is equal to 0. The test must be explicit. | ||
== Quoting == | == Quoting == |
Revision as of 16:15, 16 November 2007
String Manipulations
- To replace all substrings by another, use the following syntax:
echo ${stringZ//abc/xyz}
This would replace all occurences of abc in stringZ by xyz. The following replaces only the first match:
echo ${stringZ/abc/xyz}
Special Symbols
- "$@" expands to all command-line parameters.
- "\n" in a variable does not necessarily works as expected. Eg, no newline is created.
- \ before a newline actually escapes the newline. Thus, you can create multi-line strings or commands just by terminating a line with the \ symbol.
Tests
- -n checks if a string is not empty, -z if it is empty.
- [ is not a keyword but a command (a program!). It is recommended to use [[ in tests which is a keyword.
- Note that [[ myVariable ]] will output true even if myVariable is equal to 0. The test must be explicit.
Quoting
- If you need to expand special characters such as *, you cannot quote.
- Use single quotes rather than double quotes, especially in sed. If you use double quotes, the \ itself won't be taken as a \ for escaping, thus causing problems.
- If you write \ and then a newline, the newline will be escaped which allows you to write multiline strings.
Standard Input / Output
- "<<<" can be used to feed a string as standard input.
Command Line Utilities
- sdiff -s will generate a formatted output of the differences between two files. Very useful.
sed
- sed is a stream editor. It is extremely powerful and can do almost everything under the sun. It can:
- delete a line with command d;
- append with command a;
- use multiline strings if needed, with the standard Bash mechanism;
- use several replacements on one line, adding the option -e to all changes;