This was written at my very woke moments when I realize I’m probably going to forget about some tiny little details about bash shell if I don’t use all of them that much in the future. And also, sometimes, snippets can be handy.
These are some very basic stuffs, in case you really need them.
It’s a common thing to add headers (
shebang in nature) to shell script to designate the shell you wanna use. You can go with
bash or whatever works.
It can have parameters:
Even with PHP script, though it’s off topic.
Everything is “string”.
You wanna have literals? Gotcha covered.
# No space after variable name or after the equal sign.
Pass a variable? No problem.
# Yes, you gotta quote them
You can even use an output of a command? Coooool!
a="Today is $(date +%Y-%d-%m)"
if control flow, shell has quite a bit of history.
So, there are a lot of ways to write conditions, namely
Generally, it is written in this manner:
As for how condition is written, that’s where the “goodies” are.
# How spaces are put is very strict here
[] is not very universal, you could probably only use it with Bash or ksh. It was introduced into Bash at the version 2.02. But it is much more capable than
 in terms of expressiveness.
# You can use wildcards here. But still, spaces are very
(()) is basically doing arithmetic calculations, but its result can be used as a logic value for
if control flow.
# In `(())`, you can omit dollar sign for variables
If you understand how conditions are written for
if statement, then
while should be no problem for you. There is also another thing called
until loops, which work very much like
while loops, the only difference being
until loops only run its loops when CONDITION are NOT met.
for loops have two styles, one like C/C++, the other like python. You can also do
continue by the way.
for ((i=1; i<=100; i++))
# List values
|$0||The filename of the current script.|
|$n||These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).|
|$#||The number of arguments supplied to a script.|
|$*||All the arguments, all double quoted. If a script receives two arguments, $* is equivalent to $1 $2.|
|[email protected]||All the arguments, all individually double quoted. If a script receives two arguments, [email protected] is equivalent to $1 $2.|
|$?||The exit status of the last command executed.|
|$$||The process number of the current shell. For shell scripts, this is the process ID under which they are executing.|
|$!||The process number of the last background command.|
Get script path
Delete a directory if exits
if [ -d "$dir" ] ; then
Create a directory if it doesn’t exist
if [ ! -d "$dir" ] ; then
About this Post
This post is written by Dizy, licensed under CC BY-NC 4.0.