bash-note

bash

type
printf
declare
test []

variables

list all of the variables currently assigned by leaving out the name:
declare -p

if [[ -n $system ]] ; then
printf ‘The “system” variable is: %s\n’ “$system”
fi

remove a variable with unset

environment variables

export

parenthesis [pa·ren·the·sis || pə’renθɪsɪs]

n. 括弧, 附带, 插入语
Parentheses (()) are used to create a subshell.

cruly braces

(a) Braces ({}) are used to unambiguously identify variables. Example:
(b) Braces are also used to execute a sequence of commands in the current shell context, e.g.

barckets

A single bracket ([) usually actually calls a program named [; man test or man [ for more info. Example:
.
$ VARIABLE=abcdef
$ if [ $VARIABLE == abcdef ] ; then echo yes ; else echo no ; fi
// yes
.
The double bracket ([[) does the same thing (basically) as a single bracket, but is a bash builtin.


Especially in older shell scripts, you may sometimes see backticks ( ) used for command substitution. Bash still allows this syntax so that older scripts can run, but you should prefer the $(command) syntax tocommand` ; the former is easier to read, and much easier to perform expansions within expansions.

If a variable may not have a value in a script, you can specify a default or “fallback” value for it with the form “${myvar:-default}” , where default is the string you want to use instead of the variable’s value if it’s unset or blank.

String chopping

“${myvar#prefix}”

Extracting substrings

${var:start} or ${var:start:length}

Getting string length

The ${ #myvar} form can be used to expand to the length of a string:

Changing case

You can have a variable expand into its value with all characters uppercase or lowercase using the “${myvar^^}” and “${myvar,,}” forms,

Doing math in Bash

‘$ num_a=3
‘$ num_b=2
‘$ printf ‘The sum of the two numbers is: %u\n’ “$((num_a + num_b))”
The sum of the two numbers is: 5

bash array

bash’$ fruits=(‘apple’ ‘banana’ ‘cherry’)


--Write by Marcustar,关关雎鸠,在河之洲
目录
Download 相册