Files
linux.softwareshinobi.com/landing/docs/Bash-Scripts/004-bash-variables.md
Software Shinobi 7d9171c854
All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good
reworking content
2025-06-19 10:03:08 -04:00

1.9 KiB

Variables

Like any language, Bash uses variables. No strict data types here; a variable holds numbers or characters.

Assign a value:

name="Shinobi"

Note: No spaces around the = sign. This is critical.

Access the value using $ before the variable name:

echo $name

While optional, wrapping the name in curly braces is good practice for clarity:

echo ${name}

Both would output: Shinobi.

Now, let's build a script.

First, create the file:

touch shinobi.sh

Then, open shinobi.sh and add this content to include a variable:

#!/usr/bin/env bash

name="Shinobi"

echo "Hi there $name"

Save and exit.

Make it executable:

chmod +x shinobi.sh

Run your script:

./shinobi.sh

You'll see:

Hi there Shinobi

This script:

  • #!/usr/bin/env bash: Sets the interpreter.
  • name="Shinobi": Defines name with its value.
  • echo "Hi there $name": Outputs the welcome message using the variable.

You can use multiple variables:

#!/usr/bin/env bash

name="Shinobi"
greeting="Hello"

echo "$greeting $name"

Save and run shinobi.sh again:

./shinobi.sh

Output:

Hello Shinobi

No semicolons needed at line ends.

Command Line Parameters

Bash scripts also read variables passed directly from the command line. These are called parameters.

Run your script with inputs like this:

./shinobi.sh Troy buddy!

Now, modify your shinobi.sh file to access these parameters:

#!/usr/bin/env bash

echo "Hello there" $1   # $1: first parameter
echo "Hello there" $2   # $2: second parameter
echo "Hello there" $@   # $@: all parameters

The output for ./shinobi.sh Troy buddy! will be:

Hello there Troy
Hello there buddy!
Hello there Troy buddy!