I need to add a part to a shell script that will count down the number of command line arguments, printing one per second to the screen and reporting how many command line arguments are left (e.g., by using the shift builtin in a loop). So the screen would do a countdown 6 5 4 3 2 1 (if I had entered six command line arguments).

Also, when the last command line argument has been reached (shifted over to $1), the program will tell the user the value of the command line argument in a statement such as "The last command line argument that you entered is ______ . (whatever its value was is to be printed there.)

So far I have this code, but it only prints the first argument, and it doesn't print the numbers.

while read -n 1 -p "Press Enter to Continue.." key
     if [ "$key" = '' ]; then
         sleep $#
         shift $1
         echo "The last command line parameter you entered at the command line was: $1"
         echo "no key was pressed"

What am I doing wrong?  What should I do to fix it?

  • I got the countdown timer to work, but I'm still confused about how to use the shift command. I need whatever the last argument to be added to a sentence for example, if I had mary had a little lamb. I would need to echo: The last command-line argument is lamb. – camjace321 Jul 29 '20 at 0:07
  • I figured it out. Thanks for the help. – camjace321 Jul 29 '20 at 0:16

and it doesn't print the numbers.

$# contains the number of arguments, so use something like echo "$#" where you want it.

sleep $#

This would sleep for six seconds in on go if there are six arguments. You probably want to sleep for one second at a time instead.

shift $1

The argument to shift is the number of leading arguments to shift away. So this can remove multiple arguments at a time, or give an error if the first argument isn't numeric.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.