reworking content
All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good
All checks were successful
learn org at code.softwareshinobi.com/linux.softwareshinobi.com/pipeline/head This commit looks good
This commit is contained in:
101
landing/docs/Bash-Scripts/007-bash-arguments.md
Normal file
101
landing/docs/Bash-Scripts/007-bash-arguments.md
Normal file
@@ -0,0 +1,101 @@
|
||||
# Runtime Arguments
|
||||
|
||||
Pass data into your script at execution. Arguments follow the script name:
|
||||
|
||||
```bash
|
||||
./your_script.sh first_argument
|
||||
```
|
||||
|
||||
Inside the script, `$1` references the first argument, `$2` the second, and so on.
|
||||
|
||||
Let's see this in `arguments.sh`:
|
||||
|
||||
```bash
|
||||
touch arguments.sh
|
||||
```
|
||||
|
||||
Open `arguments.sh` and add:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
echo "Arg 1: $1"
|
||||
echo "Arg 2: $2"
|
||||
echo "Arg 3: $3"
|
||||
```
|
||||
|
||||
Save and exit. Make it executable:
|
||||
|
||||
```bash
|
||||
chmod +x arguments.sh
|
||||
```
|
||||
|
||||
Run with three arguments:
|
||||
|
||||
```bash
|
||||
./arguments.sh dog cat bird
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```bash
|
||||
Arg 1: dog
|
||||
Arg 2: cat
|
||||
Arg 3: bird
|
||||
```
|
||||
|
||||
To access *all* arguments, use `$@`. Update `arguments.sh`:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
echo "All arguments: $@"
|
||||
```
|
||||
|
||||
Save. Run again with arguments:
|
||||
|
||||
```bash
|
||||
./arguments.sh dog cat bird
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```bash
|
||||
All arguments: dog cat bird
|
||||
```
|
||||
|
||||
### Script Name (`$0`)
|
||||
|
||||
`$0` references the script itself. This is useful for logging or unique operations.
|
||||
|
||||
You can even use `$0` for self-deletion. **Handle with extreme caution!**
|
||||
|
||||
Create `self_destruct.sh`:
|
||||
|
||||
```bash
|
||||
touch self_destruct.sh
|
||||
```
|
||||
|
||||
Open `self_destruct.sh` and add:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
|
||||
echo "This script: $0 is self-destructing."
|
||||
|
||||
rm -f $0
|
||||
```
|
||||
|
||||
Save and exit. Make it executable:
|
||||
|
||||
```bash
|
||||
chmod +x self_destruct.sh
|
||||
```
|
||||
|
||||
Run it:
|
||||
|
||||
```bash
|
||||
./self_destruct.sh
|
||||
```
|
||||
|
||||
The script will print its name, then delete itself. **This is irreversible. No second chances.** Always back up before testing self-deletion.
|
||||
Reference in New Issue
Block a user