📖 Added more bash examples to cheatsheet

This commit is contained in:
Jun Wei Woon 2020-07-09 13:20:25 +08:00
parent c2499970db
commit dc6d250f05
1 changed files with 62 additions and 0 deletions

View File

@ -192,8 +192,70 @@ function fun(){
echo 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" >}} {{< expand "Credits/References" >}}
[stackoverflow1](https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash) [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) [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 >}} {{< /expand >}}