Skip to main content

Bash Cheatsheet

Multi-line Command

To execute multi-line command in bash script simple put a \ after breaking up your commands. There should be no white spaces after the backslash, else it will fail!

Every single line should be followed by a \ until you finished typing the command.

curl https://cat.png \#no spaces after!
	-o here.txt \

If-Statements

In Bash the if-statements follows the structure:

if CONDITION
then
	COMMAND
elif CONDITION
then
	COMMAND
else
	COMMAND
fi

As you can see every if chain will end with fi keyword. Every if/elif condition statement will be followed by the then keyword.

If you want to put the then on the same line with the if keyword, and because if, then, else, elif, fi are all shell keyword they cannot be used on the same-line. To fix this you have to put a ; to end the previous statement and the keyword before you can use another keyword. As an example:

if CONDITION; then
	COMMAND
fi

Conditions

Okay, now we know the basic of if-statements how do I put it into use by filling in the conditions? There are couple different ways of writing conditions, here I will only go over the most commonly used ones.

1.

# The first way is using test
if test <expressions>; then
	COMMAND
fi

Using this method you can test whether the files exists, and compare values. It has it's own set of syntax for example to check if a certain file named "foo.txt" exists then you would type test -f "foo.txt" and it will evaluate to true if only the file "foo.txt" exists.

You can also append ! to negate the expression to check the opposite. Use = to do string equality comparison.

2.

# The second way is using [] square brackets
if [ some test ]; then
	COMMAND
fi

 

 

https://unix.stackexchange.com/questions/306111/what-is-the-difference-between-the-bash-operators-vs-vs-vs

https://www.baeldung.com/linux/bash-single-vs-double-brackets

https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

https://www.geeksforgeeks.org/bash-scripting-if-statement/

https://opensource.com/article/18/5/you-dont-know-bash-intro-bash-arrays