Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zsh: access last command line argument given to a script

Tags:

zsh

I want to get the last element of $*. The best I've found so far is:

 last=`eval "echo \\\$$#"`

But that seems overly opaque.

like image 858
rampion Avatar asked Sep 20 '11 23:09

rampion


People also ask

How to access command line arguments in a shell script?

We can also access all command line arguments by shifting their position in a shell script. Like access your first command line argument with $1. Now shift arguments with 1. It means the second argument is now at first position, similarity third is at second and so on.

How do I pass a filename as a command line argument?

Instead of prompting the user for the filename, we can make the user simply pass the filename as a command line argument while running the script as follows: The first bash argument (also known as a positional parameter) can be accessed within your bash script using the $1 variable.

How to pass more than one argument to a bash script?

You can pass more than one argument to your bash script. In general, here is the syntax of passing multiple arguments to any bash script: script.sh arg1 arg2 arg3 …. The second argument will be referenced by the $2 variable, the third argument is referenced by $3, .. etc. The $0 variable contains the name of your bash script in case you were ...

What are Bash arguments in Linux?

Bash Shell arguments, bash, script, shell. A Command-line Arguments are passed after the name of a program in command-line operating systems like DOS or Linux and are passed into the program from the operating system. Shell scripts also accept command line arguments similar to nix commands.


1 Answers

In zsh, you can either use the P parameter expansion flag or treat @ as an array containing the positional parameters:

last=${(P)#}
last=${@[$#]}

A way that works in all Bourne-style shells including zsh is

eval last=\$$#

(You were on the right track, but running echo just to get its output is pointless.)

like image 86
Gilles 'SO- stop being evil' Avatar answered Jan 04 '23 05:01

Gilles 'SO- stop being evil'