Shell Script

How to Write a Shell Script to Display Command Line Argument Using $#, $@,$*,$$,$?$!

The following article demonstrates How to Write a Shell Script to Display Command Line Argument Using $#, $@,$*,$$,$?$!

Accordingly, a simple shell script that demonstrates the use of various special variables is given below.

#!/bin/bash

# Display the total number of command line arguments
echo "Total number of arguments: $#"

# Display all the command line arguments separated as individual strings using "$@"
echo "Using \"\$@\":"
for arg in "$@"; do
echo "$arg"
done

# Display all the command line arguments as a single string using "$*"
echo "Using \"\$*\":"
echo "$*"

# Display the process ID of the script using "$$"
echo "Process ID of the script: $$"

# Execute a non-existent command to set an exit status
non_existent_command
exit_status=$?

# Display the exit status of the last executed command using "$?"
echo "Exit status of last command: $exit_status"

# Display the process ID of the last background command using "$!"
sleep 5 &
background_pid=$!
echo "Process ID of last background command: $background_pid"

# Wait for background process to complete
wait $background_pid
echo "Background process has completed"

Make sure to save this script to a file, make it executable using chmod +x script_name.sh, and then run it with command line arguments.
For example, if you save the script as display_args.sh and run it like this.

./display_args.sh arg1 arg2 "arg 3" arg4

As a result, you will get the following output.

Total number of arguments: 4
Using "$@":
arg1
arg2
arg 3
arg4
Using "$*":
arg1 arg2 arg 3 arg4
Process ID of the script: <some_process_id>
./display_args.sh: line 16: non_existent_command: command not found
Exit status of last command: 127
Process ID of last background command: <background_process_id>
Background process has completed

Further Reading

How to Write a Shell Script to Display Command Line Argument Using $#, $@,$*,$$,$?$!

Cloud Computing with Amazon Web Service (AWS)

Getting Started Your Journey into Cloud With AWS

How to Work With AWS Management Console?

What are the Important Components of AWS

Understanding Amazon EC2 and How Does it Work

Features and Benefits of Amazon S3 Bucket

programmingempire

Princites

Leave a Reply

Your email address will not be published. Required fields are marked *