122 lines
1.9 KiB
Markdown
122 lines
1.9 KiB
Markdown
|
|
# Variables
|
||
|
|
|
||
|
|
Like any language, Bash uses variables. No strict data types here; a variable holds numbers or characters.
|
||
|
|
|
||
|
|
Assign a value:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
name="Shinobi"
|
||
|
|
```
|
||
|
|
|
||
|
|
> **Note:** No spaces around the `=` sign. This is critical.
|
||
|
|
|
||
|
|
Access the value using `$` before the variable name:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
echo $name
|
||
|
|
```
|
||
|
|
|
||
|
|
While optional, wrapping the name in curly braces is good practice for clarity:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
echo ${name}
|
||
|
|
```
|
||
|
|
|
||
|
|
Both would output: `Shinobi`.
|
||
|
|
|
||
|
|
Now, let's build a script.
|
||
|
|
|
||
|
|
First, create the file:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
touch shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Then, open `shinobi.sh` and add this content to include a variable:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/usr/bin/env bash
|
||
|
|
|
||
|
|
name="Shinobi"
|
||
|
|
|
||
|
|
echo "Hi there $name"
|
||
|
|
```
|
||
|
|
|
||
|
|
Save and exit.
|
||
|
|
|
||
|
|
Make it executable:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
chmod +x shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Run your script:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
./shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
You'll see:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
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:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/usr/bin/env bash
|
||
|
|
|
||
|
|
name="Shinobi"
|
||
|
|
greeting="Hello"
|
||
|
|
|
||
|
|
echo "$greeting $name"
|
||
|
|
```
|
||
|
|
|
||
|
|
Save and run `shinobi.sh` again:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
./shinobi.sh
|
||
|
|
```
|
||
|
|
|
||
|
|
Output:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
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:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
./shinobi.sh Troy buddy!
|
||
|
|
```
|
||
|
|
|
||
|
|
Now, modify your `shinobi.sh` file to access these parameters:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
#!/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:
|
||
|
|
|
||
|
|
```bash
|
||
|
|
Hello there Troy
|
||
|
|
Hello there buddy!
|
||
|
|
Hello there Troy buddy!
|
||
|
|
```
|