Skip to content
GradedJestRisk edited this page Apr 13, 2020 · 5 revisions

Table of Contents

Overview

Using bash:

Default config file is ~/.bashrc , loaded at terminal start

Shorcuts

Shortcuts

Hello, world !

Create source file helloworld.sh

#!/bin/bash
echo "hello world"

Execute:

  • sh helloworld.sh
  • sudo chmod +x helloworld.sh; ./helloworld.sh

Aliases

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

Command prompt

Alter PS1 variable in .bashrc
PS1='\u \w $ ' => USER_NAME WORKING_DIRECTORY $

To format the prompt, use ASCII escape sequence

Use escape
Open Body Close
\[ ESCAPE_SEQUENCE \]

Here's the codes

Escape sequence
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

Full list of escape codes

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

Source

constants
functions
main_function

Basics

Variable
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

Strings

Strings
Need Syntax Output
Check if string is null [[ -z "${variable_name}" ]]
Check if string is not null [[ -n "${variable_name}" ]]

Control flow

Need Syntax
Test
if [ CONDITION ] then
   ACTION 
else 
   ACTION 
fi 
Infinite loop while true; do foo; sleep 2; done

operators

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

File descriptors

Description
Name Number
0 stdin
1 stdout
2 stderr
Use
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

More on this

Function

Function
Need Syntax
Declare function function_name() { (..) }
Access parameter if [[ $1 = "foo" ]]
Call with parameter $bar = function_name $foo

Return code

Convention:

  • successful: 0
  • error: 1
  • specific error: 2 to 255, see here
List:
  • set return code:exit $RETURN_CODE
  • get return code: $?

Quickies

List:

  • execute a command frequently: while sleep <TIME_SECONDS>; do <COMMAND>; done;
Clone this wiki locally