Bash programming 101 - variables.

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
3,673
Reaction score
3,486
Credits
32,757
One off the most basic things you will ever do in a bash script, is use a variable. The world "variable" comes from the word "vary". To vary means to change. Usually variables are something that can change, but not always. There are also "static" (hard coded) variables that don't change. (Hmmm... is static-variable an oxymoron?) In any case, I use both frequently.

Here is where we start. Use an editor to make this file (vi or nano, or whatever you like)
Code:
#!/bin/bash
echo "Enter your name:"
read name
echo "Hello, $name!"

You can save this as any name you like, but typically bash shell scripts end with a .sh, like my_first_script.sh
Linux doesn't like filenames with spaces in them. It can be done, but adds un-needed complexity here. The next thing
you need to do, is make your file "executable", that just means, make it able to run. How do you do that?

Code:
 chmod +x filename.sh
Just change filename.sh to whatever you named your file above. To run it, you just type ./filename.sh. I'll explain paths and why you need the ./ later. This is a very simple script. It just asks for your name, and assigns that input to a variable called "name". It then prints out "Hello (your name).

Congratulations, you just used a variable in bash shell script. The "read" command takes input from the keyboard. Let's try something else. (I'm making up the content here as I go)

Code:
#!/bin/bash
current_date=$(date)
echo "Today's date is: $current_date"
Save this as date_example.sh, and make it executable. Run it like this... ./date_example.sh
To be honest, this example is a little un-neccesary. You could just type "date". But I wanted to assign the output of a shell command to a variable. Some variables are meant to be short-lived. Date is a good example. If my shell script got the current date and time, and then have something like like a sleep statement to wait an hour or two before I printed the date, the output would be wrong, it wouldn't be the current time.

So how do we set a static variable? (One that doesn't change).
Code:
#!/bin/bash
greeting="Hello, World!"
echo $greeting
Again save this, and make it executable. You should know how to run this by now.
How would I rewrite this script to read my name and echo out something like "Hello Ray, how are you today?"
(a clue is in our first example).

You can set the values of multiple variables in a bash shell script. There really isn't a limit of how many variables you can have.
Code:
#!/bin/bash
name="Alice"
age=30
echo "Name: $name, Age: $age"
You know the routine. Save it, make it executable and run it. How would I change this to take user input for the two variables?

You can manipulate a variable in a lot of ways, you can cut it, awk it, sed it, uppercase it, or do a hundred other things to it.
Code:
#!/bin/bash
original="hello"
uppercase=$(echo $original | tr '[:lower:]' '[:upper:]')
reversed=$(echo $original | rev)
echo "Uppercase: $uppercase"
echo "Reversed: $reversed"
echo "Original: $original"

If you change it, you will usually call it a different variable name. In the example above, I have 3 variable names, do you see them?
What are they? How did I create the last two?

Notice my original variable value didn't change. The last echo statement prints it out as it was originally.
 


Again, you can simply export the value of a variable like this.
Code:
export MY_VAR="some_value"

Sometimes having a "default" name for a variable helps.
Code:
 name=${name:-"Default Name"}

Many programming languages are what we call "typed" languages. This means you have to tell that language if a variable is a number or text, or a date, or whatever. Bash isn't a typed language. It doesn't (always) care if the value is a number, or text, or a date).

Code:
num1=5
num2=10
sum=$((num1 + num2))
echo "Sum: $sum"

It does the math in our script, because it automatically assumes that numbers are... well... numbers.
By default all variables in bash are "global" variables, meaning that the value of a variable works everywhere in my script.
But sometimes, you may want something to be a local variable, for only that specific function. There is a "local" keyword for that.

Code:
#!/bin/bash

my_function() {
    local local_var="I am local"
    echo $local_var
}

my_function
# Trying to access local_var outside the function will result in an empty output
echo $local_var

Sometimes a variable is just a temporary place holder, consider the following script.
Code:
#!/bin/bash

# Directory containing the files
directory="/path/to/your/directory"

# Loop through all .txt files in the directory
for file in "$directory"/*.txt; do
    # Get the base name of the file (without the extension)
    base_name=$(basename "$file" .txt)
    # Construct the new file name with .sh extension
    new_file="$directory/$base_name.sh"
    # Rename the file
    mv "$file" "$new_file"
    echo "Renamed $file to $new_file"
done
This script reads the filenames of all the files that end with ".txt" and changes them to ".sh". Imagine if you have hundreds of files in a directory, the base_name value would change hundreds of times.

That's all I have time for today. Next time we'll add some error handling.
 


Staff online

Members online


Top