Jan 5, 2012

[bash] tips

Not recommended is using sh < scriptname, since this effectively disables reading from
stdin within the script.

;
Command separator [semicolon]. Permits putting two or more commands on the same line.
echo hello; echo there
if [ -x "$filename" ]; then # Note the space after the semicolon.

;;
Terminator in a case option [double semicolon].

case "$variable" in
abc) echo "\$variable = abc" ;;
xyz) echo "\$variable = xyz" ;;
esac




:
null command [colon]. This is the shell equivalent of a "NOP" (no op, a do-nothing operation). It
may be considered a synonym for the shell builtin true. The ":" command is itself a Bash builtin, and
its exit status is true (0).

()
command group.
(a=hello; echo $a)
A listing of commands within parentheses starts a subshell.

#!/bin/bash
# Reading lines in /etc/fstab.
File=/etc/fstab
{
read line1
read line2
} < $File
echo "First line in $File is:"
echo "$line1"
echo
echo "Second line in $File is:"
echo "$line2"
exit 0
{
echo # End code block.
} > "$1.test" # Redirects output of everything in block to file.
{} placeholder for text. Used after xargs -i (replace strings option). The {} double curly brackets are a placeholder for output text.
ls . | xargs -i -t cp ./{} $1
# ^^ ^^
If COMMAND contains {}, then find substitutes the full path name of the selected file for "{}".
find ~/ -name 'core*' -exec rm {} \;
# Removes all core dump files from user's home directory.
# "2>/dev/null" hides error message.
2>/dev/null;
The (( )) construct expands and evaluates an arithmetic expression. If the expression evaluates as zero, it returns an exit status of 1, or "false". A non-zero expression returns an exit status of 0, or "true". This is in marked contrast to using the test and [ ] constructs The == comparison operator behaves differently within a double-brackets test than within single brackets.
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.