Files
linux.softwareshinobi.com/landing/docs/Bash-Scripts/007-bash-arguments.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.4 KiB

Runtime Arguments

Pass data into your script at execution. Arguments follow the script name:

./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:

touch arguments.sh

Open arguments.sh and add:

#!/usr/bin/env bash

echo "Arg 1: $1"
echo "Arg 2: $2"
echo "Arg 3: $3"

Save and exit. Make it executable:

chmod +x arguments.sh

Run with three arguments:

./arguments.sh dog cat bird

Output:

Arg 1: dog
Arg 2: cat
Arg 3: bird

To access all arguments, use $@. Update arguments.sh:

#!/usr/bin/env bash

echo "All arguments: $@"

Save. Run again with arguments:

./arguments.sh dog cat bird

Output:

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:

touch self_destruct.sh

Open self_destruct.sh and add:

#!/usr/bin/env bash

echo "This script: $0 is self-destructing."

rm -f $0

Save and exit. Make it executable:

chmod +x self_destruct.sh

Run it:

./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.