-
Notifications
You must be signed in to change notification settings - Fork 0
bash
GradedJestRisk edited this page Apr 13, 2020
·
5 revisions
Using bash:
Default config file is ~/.bashrc
, loaded at terminal start
Create source file helloworld.sh
#!/bin/bash echo "hello world"
Execute:
sh helloworld.sh
sudo chmod +x helloworld.sh; ./helloworld.sh
Overview
- list
alias
- add
alias ALIAS_NAME='COMMAND'
- remove
unalias ALIAS_NAME
- run without alias
\command
- define in terminal:
- add to specific rc file
- can be included in
.bash_aliases
- test without closing termninal
source .bash_aliases
Alter PS1 variable in .bashrc
PS1='\u \w $ '
=> USER_NAME WORKING_DIRECTORY $
To format the prompt, use ASCII escape sequence
Open | Body | Close | |
---|---|---|---|
\[
|
ESCAPE_SEQUENCE
|
\]
|
Here's the codes
Need | Syntax | Full (use around $foo) | |
---|---|---|---|
red |
\e[31m
|
\[\e[31m$foo\]
|
|
blue |
\e[36m
|
\[\e[36m$foo\
|
|
bold |
\e[1m
|
\[\e[1m$foo\
|
|
reset |
\e[0m
|
No use with $foo
|
Always add \[\e[0m\]
at end of PS1
To get local-function feedback
PS1='$(FUNCTION_NAME) :'
To dynamically return color-code
set_bash_prompt(){ PS1="[\w] $(COLORCODING_FUNCTION_NAME) \$ " } PROMPT_COMMAND=set_bash_prompt
constants functions main_function
Need | Syntax | Output | |
---|---|---|---|
Declare variable (optional) |
def variable_name
|
||
Assign variable |
variable_name=Foo
|
||
Use variable |
echo value of variable_name is $variable_name
|
value of variable_name is Foo
|
Need | Syntax | Output | |
---|---|---|---|
Check if string is null |
[[ -z "${variable_name}" ]]
|
||
Check if string is not null |
[[ -n "${variable_name}" ]]
|
Need | Syntax |
---|---|
Test |
if [ CONDITION ] then ACTION else ACTION fi |
Infinite loop | while true; do foo; sleep 2; done |
List:
- -eq : is equal to
- -ne : is not equal to
- -gt : is greater than
- -ge : is greater than or equal to
- -lt : is less than
- -le : is less than or equal to
Name | Number | |
---|---|---|
0 | stdin | |
1 | stdout | |
2 | stderr |
Need | Syntax | |
---|---|---|
Redirect and append stdout to file FILENAME |
1>>filename
|
|
Redirect both stdout and stderr to file FILENAME |
&>FILENAME
|
|
Redirects stderr to stdout. |
2>&1
|
Need | Syntax | |
---|---|---|
Declare |
function function_name() { (..) }
|
|
Access parameter |
if [[ $1 = "foo" ]]
|
|
Call with parameter |
$bar = function_name $foo
|
Convention:
- successful: 0
- error: 1
- specific error: 2 to 255, see here
- set return code:
exit $RETURN_CODE
- get return code:
$?
List:
- execute a command frequently:
while sleep <TIME_SECONDS>; do <COMMAND>; done;