#8 Variables and bash scripts
$VAR, export, loops
Environment variables
The system maintains environment variables that contain useful information. You access them with the $ prefix:
$ echo $HOME
/home/user
$ echo $USER
userSome common variables: $HOME (home directory), $USER (username), $PATH (executable paths), $PWD (current directory).
Declaring your own variables
You create a variable using the format NAME=value. Important: no spaces around the = sign!
$ NAME="Alice"
$ echo $NAME
Alice
$ FILE="report.txt"
$ cat $FILEVariables created this way are only visible in the current shell.
export -- Share variables
By default, a variable is not passed to child processes (scripts, subshells). To make it available everywhere, use export:
$ export MY_VAR="test"
$ echo $MY_VAR
test
# MY_VAR is now accessible in scripts launched from this shellCreating a bash script
A bash script is a text file containing a series of commands. The first line must be the shebang #!/bin/bash which indicates which interpreter to use:
#!/bin/bash
# For loop
for NAME in Alice Bob Charlie; do
echo "Hello $NAME!"
doneYou run the script with bash script.sh or, after making it executable with chmod +x, directly with ./script.sh:
$ bash script.sh
Hello Alice!
Hello Bob!
Hello Charlie!For loop and if condition
The for loop allows you to repeat commands for each item in a list:
for FILE in *.txt; do
echo "Processing $FILE"
doneThe if structure allows you to execute code based on a condition:
if [ -f "notes.txt" ]; then
echo "The file exists"
else
echo "File not found"
fiArithmetic operations
Bash allows you to perform calculations with the $(( )) syntax:
$ echo $((2 + 3))
5
$ echo $((10 * 4))
40Summary
NAME="value" # Declare a variable
echo $NAME # Use a variable
export NAME="value" # Export for subprocesses
bash script.sh # Run a script
./script.sh # Run (if chmod +x)
echo $((2 + 3)) # Arithmetic operationYour turn
Try creating variables, using export, and running bash script.sh in the terminal below.