Arguments can be added to a bash script after the script’s name. Once provided they can be accessed by using
$(position in the argument list). For example, the first argument can be accessed with
$1, the second with
$2, the third with
#!/bin/bash# For a script invoked by saycolors red green blue# echoes redecho $1# echoes greenecho $2# echoes blueecho $3
Variables in a bash script are set using the
= sign and accessed using
read command can be used to prompt the user for input. It will continue to read user input until the Enter key is pressed.
Some prompt text can also be specified using
-p with the
#!bin/bashecho "Press Enter to continue"readread -p "Enter your name: " name
Bash script files start with
#!/bin/bash. This special line tells the computer to use bash as the intepreter.
Aliases can be created using the keyword
alias. They are used to create shorter commands for calling bash scripts. They can also be used to call bash scripts with certain arguments.
# For example, to create an alias that invokes the saycolor# script with the argument "green", the following syntax is used:alias saygreen='./saycolors.sh "green"'
Reusuable sets of bash terminal commands can be created using bash scripts. Bash scripts can run any command that can be run in a terminal.
In bash scripting, strings are compared using the
== (Equal) and
!= (Not equal) operators.
#!bin/bashword1="Hello"word2="Hello"word3="hello"if [ $word1 == $word2 ]thenecho "Strings are equal"fiif [ $word1 != $word3 ]thenecho "Strings are not equal"fi