devoalda.gitlab.io/content/en/posts/bash_cheatsheet.md

262 lines
4.2 KiB
Markdown

---
author: "Devoalda"
authorEmoji: 🐺
title: "Bash Cheatsheet"
date: 2020-07-06T16:47:03+08:00
description: Simple Bash Cheatsheet
draft: false
hideToc: false
enableToc: true
enableTocContent: true
tocPosition: inner
tocLevels: ["h1", "h2", "h3"]
tags:
- bash
- linux
- script
- cheetsheet
series:
- Bash
categories:
- bash
- script
image: images/postImages/Bash_256x256.png
---
# Introduction
This is a simple bash script cheatsheet.
# Variables
## Define variables
```bash
abc=123
hello=321
qwerty=asdf
```
### Assign output of command to variable
``` bash
music=$(mpc)
```
### Argument
```bash
word=$1
```
### Argument and default value
``` bash
words=${1-hello} # If variable not set or null, use default.
FOO=${VARIABLE:=default} # If variable not set or null, set it to default.
```
{{< alert theme="info" dir="ltr" >}}
Ensure no spaces between variable name and value
{{< /alert >}}
## View variable content
```bash
$ echo $abc
# outputs: 123
$ echo "$(echo "upg")"
# outputs: upg
$ echo '$(echo "upg")'
# outputs: $(echo "upg")
```
# Loops
## For loop
``` bash
for i in {1..5}
do
echo "Hello $i"
done
```
### {START..END..INCREMENT}
``` bash
for i in {0..10..2}
do
echo "Hello $i"
done
```
### Files
``` bash
for file in $HOME
do
echo $file
done
```
## While loop
``` bash
while [ condition ]
do
echo "hello"
done
```
### Infinite while loop
``` bash
while true
do
echo "hello"
done
```
{{< alert theme="info" dir="ltr" >}}
Hit CTRL-C to stop the loop
{{< /alert >}}
### Read File
``` bash
#!/usr/bin/env bash
FILE=${1-hello.txt}
while read line
do
# use $line variable to process line
echo $line
done < "$FILE"
```
# If Else Loop
``` bash
if [ condition ]; then
echo 1
elif [ condition2 ]; then
echo 2
else
echo 3
fi
```
# Conditions
| Operator | Description |
|-----------|--------------------------|
| -eq | Equal |
| -lt | Less than |
| -le | Less than or equal to |
| -gt | Greater than |
| -ge | Greater than or equal to |
| == | 2 Strings equal |
| != | 2 Strings not equal |
| ! | Statement is false |
| -d | Directory is present |
| -e | File is present |
| -f | File is present |
| -z "$1" * | Check for empty argument |
{{< alert theme="info" dir="ltr" >}}
\* Note the space between the operator and argument
```bash
[ -z "$1" ]
```
{{< /alert >}}
## Condition Usage Examples
``` bash
if [[ "$1" == "bash" && "$2" = "shell" ]]; then
echo "$1 $2"
elif [ "$1" == "bash" ]; then
echo "$1"
elif [ -e "$HOME/hello.txt" ]
echo "File Present"
elif [ ! -d "$HOME/Documents" ]
echo "Directory NOT Present"
else
echo Condition
fi
```
# Case
``` bash
word=$1
case "$word" in
hello)
echo hello
;;
bye)
echo bye
;;
*)
echo Universal
;;
esac
```
# Functions
``` bash
function fun(){
echo fun
}
```
# String Manipulation
## Concatenate Strings
``` bash
string1=abc
string2=def
echo "$string1string2ghi jkl"
# Outputs: abcdefghi jkl
```
## Extract String
``` bash
string="hello/devoalda/devo.com"
# Get Filename
echo ${string##*/}
# Outputs: devo.com
# Get Path
echo ${string%/*}
# Outputs: hello/devoalda
# Get File Extension
echo ${string##*.}
# Outputs: com
# Multiple Operations
NAME=${string##*/} # remove part before last slash
echo ${NAME%.*} # from the new var remove the part after the last period
# Outputs: devo
```
## String contain substring
{{< tabs bash python>}}
{{< tab >}}
### bash
``` bash
echo "This is a bash script" | grep "bash"
# True if "bash" is in sentence
test='GNU/Linux is an operating system'
if [[ $test == *"Linux"* ]]; then
echo "true"
fi
```
{{< /tab >}}
{{< tab >}}
### python
``` python
test='GNU/Linux is an operating system'
if "Linux" in test:
print('true')
else:
print('false')
```
{{< /tab >}}
{{< /tabs >}}
{{< expand "Credits/References" >}}
[stackoverflow1](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash)
[stackoverflow2](https://stackoverflow.com/questions/2013547/assigning-default-values-to-shell-variables-with-a-single-command-in-bash)
[stackoverflow3](https://stackoverflow.com/a/19482947)
{{< /expand >}}