Post

Linux bash script - variables, command outputs, and determine statements

Linux bash script - variables, command outputs, and determine statements

Variables

Variables should be named as the combination of numbers, letters, and underscore.

Special variables

Here is the list of special variables and their meanings, which should not be occupied when programming.

VARIABLESMEANINGS
$0Name + path of the current script
$nn is an integer > 0. External variables, entered after the script name before executing
$#The number of external variables
$*All the external variables, "$1", "$2", …
"$*"All the external variables as a single variable, "$1 $2 ..."
$@, "$@"Same as $*
$?Exit status of the last command. Successful, =0; Failed, >0
$$PID of the current process

Environmental variables

The specific definition of environmental variables depend on the specific environment. Here are some common environmental variables.

VARIABLESMEANINGS
$HOMEHome directory
$USERUser name
$PWDCurrent directory
$PATHPath to executables
$LD_LIBRARY_PATHPath to libraries to be linked with -D -l flag
$INCLUDEPath to header files to be included with -I flag

Variable operations

List variables are defined as (elem1 elem2 ...). Common operations for a list variable $LIST:

OPERATIONSMEANINGS
${LIST[n]}n >= 0, the nth element of $LIST
$LISTThe first element of $LIST, ${LIST[0]}
${LIST[@]}, ${LIST[*]}All the elements of $LIST
${#LIST[@]}The length of $LIST

String variables can be truncated from a specified character or a specified index. Taking link='spica-vir.github.io' as an example:

OPERATIONSMEANINGS
${link%.*}Cut the right most ‘.’ and the content on its right, spica-vir.github
${link%%.*}Cut the left most ‘.’ and the content on its right, spica-vir
${link#*.}Cut the left most ‘.’ and the content on its left, github.io
${link##*.}Cut the right most ‘.’ and the content on its left, io
${link: 3:6}Return to the string with indices 3~6, including 2 ends, ca-v
${link: 6}Return to the string starting from the index 6, vir.github.io
${link: -6}Return to the string of the last 6 characters, hub.io

Command outputs

The output of commands can be redirected using the symbols listed below:

SYMBOLSMEANINGS
0Standard input
1Standard output
2Standard error
command > fileRedirect the standard output of ‘command’ to a newly created ‘file’
command >> fileRedirect the standard output of ‘command’ to the end of ‘file’. If ‘file’ does not exist, create it
command >& file, command &> fileRedirect the standard output and standard error of ‘command’ to a newly created ‘file’
2>&1Copy the behavior of standard output and use it for standard error
: > fileCreate an empty file

Analysis:

1
2
3
4
# Command 1
$ command > file.out 2>&1
# Command 2
$ command 2>&1 > file.out
  • Command 1: Standard output redirected to ‘file.out’; Copied to standard error; Standard error redirected to ‘file.out’. —> Output and error printed in ‘file.out’.
  • Command 2: Standard output by default printed on screen; Copied to standard error; Standard output redirected to ‘file.out’. —> Output printed in ‘file.out’, error printed on screen.

Determine statements

Determine statements are important for both ‘if’ sentences and ‘while’ loops. The differences between statements acting on variables / files, or numbers / strings should be noticed.

For files and directories

OPERATORSMEANINGS
-eFile / directory exists, True
-sFile / directory not empty, True
-dIs a directory, True
-fIs a regular file, True
-h, -LIs a soft link, True
-rReadable, True
-wWritable, True
-xExecutable, True

For variables

OPERATORSMEANINGS
$variableVariable exists, True
-nVariable is not empty, True
-zVariable is empty, True

For strings

For string comparison, in case of spaces, adding “” to protect variables is recommended. Besides, == is preferred to -eq due to the same reason.

OPERATORMEANING
"$string_1" == *"$string_2"*If $string_2 is contained within $string_1, True

For numbers

To compare integer values in if statement, use:

COMMANDMEANING
==, -eqEqual to
-gtGreater than
-ltLess than
-geGreater than or equal to
-leLess than or equal to

To calculate integers, use:

COMMANDMEANING
c=$(( a + b ))Save the sum of $a and $b to $c. Note there is no dollar sign in parenthesis

To compare float numbers, bc command should be used. bc command returns an integer variable, and it cannot be used as determine statements, otherwise the statement can only tell whether the specific variable is empty.

COMMANDMEANING
$(echo "$a==$b" | bc) == 1Float equal
$(echo "$a>$b" | bc) == 1Float greater than

Use bc to run float calculations:

COMMANDMEANING
echo "scale=2;$a+$b" | bcFloat sum, rounded to 2 decimal places
This post is licensed under CC BY 4.0 by the author.