Home   Notes   Contact Me

Bash shell

Local

External


History

Commands

CommandDescription
control-RSearch Command History in Reverse (the prefered direction)

Settings

# set num lines of history kept in memory export HISTSIZE=5000 # set num lines of history persisted in a file export HISTFILESIZE=5000 # ?? HISTFILE

Useful Links


stderr Piping

$cmd > stdout.txt 2> stderr.txt $cmd 2>&1 > stdoutAndErr.txt # alternate(?) method: $cmd > stdoutAndErr.txt 2>&1 $cmd 2>&1 | stdoutAndErr

Disable Screen Blank

# This needs to happen: setterm -blank 0 # try putting it in /etc/bashrc

Disable Beep

# This needs to happen: setterm -blength 0 # try putting it in /etc/bashrc

String Manipulation

OperationHow to
string length${#parameter}
substitute ${parameter//pattern/string} - all occurances
${parameter/pattern/string} - 1 time
substitutes newStr for pattern in parameter
parameter is expanded like with file name expansion (???)
if pattern starts with # it matches at the beginning of parameter only
if pattern starts with % it matches at the end of parameter only
if string is empty matches are deleted, in this case the '/' before string is optional
there are some sort of special cases with '@' and '*' either in or as parameter (? maybe works with the command line parameters in these cases ?)

Customizing

To customize bash, like adding more directories to the search path, modify ~/.bash_profile


Case Statement


COUNT=three
case $COUNT in
	1)
		echo 1
		::
	three)
		echo it is three
		::
	*)
		echo it is not 1 or 'three'
		::
esac

Command stuff

TEXT_OUT=`ls`Getting the output of a command into a variableuse single back quotes

Removing Leading Chars

This removes the first char, but making a substring starting from the 2nd char
echo ${myVar:2}

Conditional Expressions

6.4 Bash Conditional Expressions 
Conditional expressions are used by the [[ compound command and the test and [ builtin commands. 

Expressions may be unary or binary.
Unary expressions are often used to examine the status of a file. 
There are string operators and numeric comparison operators as well. 
If the file argument to one of the primaries is of the form `/dev/fd/N', 
then file descriptor N is checked. If the file argument to one of the primaries is 
one of `/dev/stdin', `/dev/stdout', or `/dev/stderr', file descriptor 0, 1, or 2, respectively, 
is checked. 
-a file True if file exists.
-b file True if file exists and is a block special file.
-c file True if file exists and is a character special file.
-d file True if file exists and is a directory.
-e file True if file exists.
-f file True if file exists and is a regular file.
-g file True if file exists and its set-group-id bit is set.
-h file True if file exists and is a symbolic link.
-k file True if file exists and its "sticky" bit is set.
-p file True if file exists and is a named pipe (FIFO).
-r file True if file exists and is readable.
-s file True if file exists and has a size greater than zero.
-t fd True if file descriptor fd is open and refers to a terminal.
-u file True if file exists and its set-user-id bit is set.
-w file True if file exists and is writable.
-x file True if file exists and is executable.
-O file True if file exists and is owned by the effective user id.
-G file True if file exists and is owned by the effective group id.
-L file True if file exists and is a symbolic link.
-S file True if file exists and is a socket.
-N file True if file exists and has been modified since it was last read.
file1 -nt file2 True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.
file1 -ot file2 True if file1 is older than file2, or if file2 exists and file1 does not.
file1 -ef file2 True if file1 and file2 refer to the same device and inode numbers.
-o optname True if shell option optname is enabled. The list of options appears in the description of the `-o' option to the set builtin (see section 4.3 The Set Builtin).
-z string True if the length of string is zero.
-n string
or
string
True if the length of string is non-zero.
string1 == string2 True if the strings are equal. `=' may be used in place of `==' for strict POSIX compliance.
string1 != string2 True if the strings are not equal.
string1 < string2 True if string1 sorts before string2 lexicographically in the current locale.
string1 > string2 True if string1 sorts after string2 lexicographically in the current locale.
arg1 OP arg2 OP is one of `-eq', `-ne', `-lt', `-le', `-gt', or `-ge'. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers.

Default Value, assigning

${TARGET_SYSTEM="petritis@172.16.0.176"}

For loop

# set form:
#for name [in words ...]; do commands; done
for ITEM in one two three ; do echo $ITEM ; done

for ITEM in one two three
do
	echo $ITEM
done

#output is
one
two
three

# arithmatic form:
for (( expr1 ; expr2 ; expr3 )) ; do commands ; done

Functions, user defined

[ function ] name () { command-list; }

function show() {
    echo all params $*
    local LOCALVAR=$1
    echo $LOCALVAR
    
    return 3
}

Tokenizing

# Declare an Array Variable (TOKEN):
declare -a TOKEN

# Assign the string with delimiters in it to TOKEN
TOKEN=("one two three")

# You can access the elements like this:
echo ${TOKEN[0]}
echo ${TOKEN[1]}
echo ${TOKEN[2]}

# Makes it one word (using the first delimiter in IFS as the seperator)
echo ${TOKEN[*]}

# Expands each word seperately
echo ${TOKEN[@]}


Special Symbols

SymbolDescription
$#Number of commandline args (not including the commands name)
$1command line arg #1
$2command line arg #2
$*Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
$@Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .... When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
$?Expands to the exit status of the most recently executed foreground pipeline.
$-(A hyphen.) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the `-i' option).
$$Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the invoking shell, not the subshell.
$!Expands to the process ID of the most recently executed background (asynchronous) command.
$0Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see section 3.8 Shell Scripts), $0 is set to the name of that file. If Bash is started with the `-c' option (see section 6.1 Invoking Bash), then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.
$_(An underscore.) At shell startup, set to the absolute filename of the shell or shell script being executed as passed in the argument list. Subsequently, expands to the last argument to the previous command, after expansion. Also set to the full pathname of each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

While loop

X=0
while [ $X -le 2 ]
do
    echo in loop
    sleep 10
done

If

See Conditional Expressions for more useful info.

X=one
Y=two

if [ $X = $Y ] ;
then
  echo same
else
  echo dif
fi

Y=one

if [ $X = $Y ] ; then echo same ; fi

File Existance

if [ -e $FILE ] ; then
    echo $FILE exists
fi

if [ ! -d $DIR ] ; then
    echo $DIR does NOT exist
fi


Variable Manipulation

3.5.3 Shell Parameter Expansion

The `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion.

The basic form of parameter expansion is ${parameter}. The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character that is not to be interpreted as part of its name.

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exception to this is the expansion of ${!prefix*} described below.

In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

When not performing substring expansion, Bash tests for a parameter that is unset or null; omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both existence and that the value is not null; if the colon is omitted, the operator tests only for existence.

${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. Positional parameters and special parameters may not be assigned to in this way.
${parameter:?word}
If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.
${parameter:+word}
If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
${parameter:offset}
${parameter:offset:length}
Expands to up to length characters of parameter starting at the character specified by offset. If length is omitted, expands to the substring of parameter starting at the character specified by offset. length and offset are arithmetic expressions (see section 6.5 Shell Arithmetic). This is referred to as Substring Expansion. length must evaluate to a number greater than or equal to zero. If offset evaluates to a number less than zero, the value is used as an offset from the end of the value of parameter. If parameter is `@', the result is length positional parameters beginning at offset. If parameter is an array name indexed by `@' or `*', the result is the length members of the array beginning with ${parameter[offset]}. Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1.
${!prefix*}
Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable.
${#parameter}
The length in characters of the expanded value of parameter is substituted. If parameter is `*' or `@', the value substituted is the number of positional parameters. If parameter is an array name subscripted by `*' or `@', the value substituted is the number of elements in the array.
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern just as in filename expansion (see section 3.5.8 Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the `#' case) or the longest matching pattern (the `##' case) deleted. If parameter is `@' or `*', the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the `%' case) or the longest matching pattern (the `%%' case) deleted. If parameter is `@' or `*', the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
${parameter/pattern/string}
${parameter//pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. In the first form, only the first match is replaced. The second form causes all matches of pattern to be replaced with string. If pattern begins with `#', it must match at the beginning of the expanded value of parameter. If pattern begins with `%', it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is `@' or `*', the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.