Sure! Here are a few examples demonstrating the use of $@ in shell scripts:
Example 1: Basic Usage
Create a script named print_args.sh:
#!/bin/bash
echo "All arguments: $@"
Run the script with arguments:
./print_args.sh arg1 arg2 "arg 3" arg4
Output:
All arguments: arg1 arg2 arg 3 arg4
Example 2: Using "$@" for Quoting
Create a script named print_args_quoted.sh:
#!/bin/bash
for arg in "$@"; do
echo "Argument: $arg"
done
Run the script:
./print_args_quoted.sh arg1 "arg 2" arg3
Output:
Argument: arg1
Argument: arg 2
Argument: arg3
Example 3: Counting Arguments
Create a script named count_args.sh:
#!/bin/bash
echo "Number of arguments: $#"
echo "Arguments: $@"
Run the script:
./count_args.sh one two three
Output:
Number of arguments: 3
Arguments: one two three
Example 4: Passing Arguments to Another Command
Create a script named process_args.sh:
#!/bin/bash
echo "Processing the following arguments:"
echo "$@"
Run the script:
./process_args.sh file1.txt file2.txt
Output:
Processing the following arguments:
file1.txt file2.txt
These examples illustrate how $@ can be used to handle and manipulate command-line arguments in shell scripts. If you have any specific scenarios in mind or further questions, let me know!
