I am very new to Bash scripting, can someone explain to me how the $# and $? work in the following code?
#!/bin/bash
ARGS=3 # Script requires 3 arguments.
E_BADARGS=85 # Wrong number of arguments passed to script.
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` old-pattern new-pattern filename"
exit $E_BADARGS
fi
old_pattern=$1
new_pattern=$2
if [ -f "$3" ]
then
file_name=$3
else
echo "File \"$3\" does not exist."
exit $E_BADARGS
fi
exit $?
From Learn Bash in Y minutes:
From https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
$#
shows the number of the script's arguments$?
shows the last script's return valueabout arguments:
echo "ARG[$#]"
beforeif
and then execute the script likethe ouput will be
and so on
the ouput of
$?
could be also used on the command line: