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

3.1 KiB

author authorEmoji title date description draft hideToc enableToc enableTocContent tocPosition tocLevels tags series categories image
Devoalda 🐺 Bash Cheatsheet 2020-07-06T16:47:03+08:00 Simple Bash Cheatsheet false false true true inner
h1
h2
h3
bash
linux
script
cheetsheet
Bash
bash
script
images/postImages/Bash_256x256.png

Introduction

This is a simple bash script cheatsheet.

Variables

Define variables

abc=123
hello=321
qwerty=asdf

Assign output of command to variable

music=$(mpc)

Argument

word=$1

Argument and default value

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

$ echo $abc
# outputs: 123
$ echo "$(echo "upg")"
# outputs: upg
$ echo '$(echo "upg")'
# outputs: $(echo "upg")

Loops

For loop

for i in {1..5}
do
	echo "Hello $i"
done

{START..END..INCREMENT}

for i in {0..10..2}
do 
	echo "Hello $i"
done

Files

for file in $HOME
do
	echo $file
done

While loop

while [ condition ]
do
	echo "hello"
done

Infinite while loop

while true
do
	echo "hello"
done

{{< alert theme="info" dir="ltr" >}} Hit CTRL-C to stop the loop {{< /alert >}}

Read File

#!/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

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
-z "$1" * Check for empty argument

{{< alert theme="info" dir="ltr" >}} * Note the space between the operator and argument

[ -z "$1" ]

{{< /alert >}}

Condition Usage Examples

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

word=$1

case "$word" in
	hello)
		echo hello
		;;

	bye)
		echo bye 
		;;

	*)
		echo Universal
		;;
esac

Functions

function fun(){ 
	echo fun
}

{{< expand "Credits/References" >}} stackoverflow1 stackoverflow2 {{< /expand >}}