bash script template
#!/bin/bash echo hello world
Here is what the above code is Doing:
1. The first line is a shebang. It tells the computer that this file is a bash script.
2. The second line is a comment. It’s ignored by the computer.
3. The third line is a command. It prints the text “hello world” to the screen.
Now, let’s run the script.
“`
$ ./hello.sh
hello world
“`
## Variables
Variables are a way to store information.
“`
$ name=”John”
$ echo $name
John
“`
## Functions
Functions are a way to group commands.
“`
$ function hello {
> echo “hello world”
> }
$ hello
hello world
“`
## Conditionals
Conditionals are a way to make decisions.
“`
$ name=”John”
$ if [ $name = “John” ]; then
> echo “Hello John”
> else
> echo “Hello stranger”
> fi
Hello John
“`
## Loops
Loops are a way to repeat commands.
“`
$ for i in 1 2 3 4 5; do
> echo $i
> done
1
2
3
4
5
“`
## Arrays
Arrays are a way to store multiple values.
“`
$ names=(“John” “Paul” “George” “Ringo”)
$ echo ${names[0]}
John
“`
## Hashes
Hashes are a way to store key-value pairs.
“`
$ declare -A names
$ names=([first]=”John” [last]=”Lennon”)
$ echo ${names[first]}
John
“`
## Input
Input is a way to get data from the user.
“`
$ read -p “What is your name? ” name
What is your name? John
$ echo “Hello $name”
Hello John
“`
## Exit Status
Exit status is a way to communicate the success of a command.
“`
$ ls does-not-exist.txt
ls: cannot access ‘does-not-exist.txt’: No such file or directory
$ echo $?
1
“`
## Standard Input
Standard input is a way to send data to a command.
“`
$ echo “John” | wc -c
4
“`
## Standard Output
Standard output is a way to get data from a command.
“`
$ echo “John”
John
“`
## Standard Error
Standard error is a way to get error messages from a command.
“`
$ ls does-not-exist.txt
ls: cannot access ‘does-not-exist.txt’: No such file or directory
“`
## Redirection
Redirection is a way to send output to a file.
“`
$ echo “John” > name.txt
$ cat name.txt
John
“`
## Pipes
Pipes are a way to send the output of one command to another command.
“`
$ echo “John” | wc -c
4
“`
## Background Jobs
Background jobs are a way to run a command without waiting for it to finish.
“`
$ sleep 10 &
[1] 1234
$ jobs
[1]+ Running sleep 10 &
“`
## Signals
Signals are a way to send a