Bash stands for “Bourne Again SHell”, is a replacement/improvement of the original Bourne shell (sh).

Today finished a phone interview with Comcast and scheduled onsite. They asked me about Bash and OOD/P.

Then I think I should write a Bash Note so that I can easily look them up next time.

Cheatsheet: https://github.com/skywind3000/awesome-cheatsheets

  • pwd

  • ssh user@host

  • ssh -p port user@host

  • whoami # return current username

  • passwd # allow current user

  • finger username # Displays information about user.

  • uname -a # show kernel info

  • man command # show manual

  • df # show disk info

  • ps # show your processes

  • kill PID # kill process by process ID

  • killall processname # kill process by process name

  • top # show current process

  • whois domain # get domain info

  • dig domain # get DNS info of a domain

  • wget file # download file

  • scp source_file user@host:directory/target_file # copy file from local to remote

  • copy file from remote host to local

    1
    2
    scp user@host:directory/source_file target_file
    scp -r user@host:directory/source_folder farget_folder
  • also accepte port

    1
    scp -P port user@host:directory/source_file target_file

Example of Shell programming

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash
str="hello world" # no space before or after =
function hello {
echo $1
}
hello "$str" # use "" to ensure $str be passed as a full string
# some ways to assign variables
array[0] = 9
array[1] = 8
array[2] = 7
array=([2]=7 [0]=8 [1]=9)
array(7 8 9)
echo ${array[2]} # show variables with specific index
unset array

IF

1
2
3
4
5
if [expression]; then
will execute only if expression is true
else
will execute if expression is false
fi

case

1
2
3
4
5
6
7
case expression in
pattern1 )
statements ;;
pattern2 )
statements ;;
...
esac

Loop

3 kinds of loop

1
2
3
4
5
6
7
8
9
10
11
12
for x := 1 to 10 do
begin
statements
end
for name [in list]
do
statements that can use $name
done
for (( initialisation ; ending condition ; update ))
do
statements...
done
1
2
3
while condition; do
statements
done
1
2
3
until condition; do
statements
done

Debugging

1
2
3
bash -n scriptname # won't run, grammer checking only
bash -v scriptname
bash -x scriptname

something else

edit .bashrc

1
2
3
echo $PS1 # shown the current prompts
ps1_old=$PS1 # back up
PS1="😳 \w: "

Then run source ~/.bashrc to execute

If you want to auto load .bashrc when open a new terminal, edit .bash_profile (or .zshrc for me)

1
2
3
4
# The next line enables shell include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi